/*** GLOBAL VARIABLES ***/
var logging = false;
var url_params = Object.fromEntries(new URLSearchParams(window.location.search));
if (url_params.logging == "true") { 
	logging = true;
	console.log("Additional Console Logs enabled for more information - still no sensitive information to be logged here.");
}
var targeting_enabled = false;
var targeting_set = false;
var activeCookies = checkCookie("OptanonConsent");
if (logging == true) {
	console.log("OneTrust Cookie Initially : "+activeCookies);
}
var w = '',
    h = '',
    c = 0,
    timeout = false, // holder for timeout id
    delay = 100, // delay after event is "complete" to run callback
    calls = 0;
old_width = 0;
old_height = 0;
var onload_function_init = false;
/* Qualtrics Variables */
var qualtrics_locale = "";
var isOAC = "";
var user_name = "";
var user_email = "";
var user_role = "";
var article_id = "";
var userAccData = "notset";
var csHeaderHeight = '57px';
var tabletBreakpoint = 1400;
var tabletBreakpointSet = false;
var mobileBreakpoint = 481;
var mobileBreakpointSet = false;
var recursiveCalls = 0;
var supportRecursiveCalls = 0;
var contactSupportWidth = 140;
var openedChatbot = false;
// Format is X:Y
// Both X,Y are strings
// X = The URL you want to redirect off of
// Y = The URL you want to redirect to if the current url == X
var base_url = window.location.origin;
var redirects = {
	"/hc/requests/new":"/hc?id=new_request&sys_id=cb06ab4b8702255089a37408dabb3555",
	"/hc/requests/new/":"/hc?id=new_request&sys_id=cb06ab4b8702255089a37408dabb3555",
	"/hc/requests":"/hc?id=request_list",
	"/hc/requests/":"/hc?id=request_list",
	"/hc/10dlc":"/hc?id=10dlc",
	"/10dlc":"/hc?id=10dlc"
};
var current_path = window.location.pathname;

if (redirects[current_path] != undefined) {
	window.location.replace(base_url+redirects[current_path]);
}
setTargetingVariable();
if (logging == true) {
	console.log("Targeting Enabled : "+targeting_enabled);

}

/*** EVENT HANDLERS ***/
document.addEventListener('DOMContentLoaded', function(e) {
	//call this function on page load
	ready();
	onResize();
	accordionToggle();
});

/*** WINDOW.RESIZE EVENT LISTENER ***/
window.addEventListener('resize', function() {
    // clear the timeout
    clearTimeout(timeout);
    // start timing for event "completion"
    timeout = setTimeout(onResize, delay);
});

/*** GLOBAL FUNCTIONS ***/

async function ready() {

	var params = getQueryParams (document.location.search);

	/** Hi Bugzilla - Fix bug where syncStatus endpoint returns URL parameters after anchor link (https://bugzilla.mozilla.org/show_bug.cgi?id=1947693) */
	var tURL = new URL(window.location.href); // temporary url that we can modify if need be
	var tParams = tURL.searchParams; // search parameters
	var tHash = tURL.hash; // url hash
	/** If the current hash includes & then we know that URL parameters were mistakenly appended to the end */
	if (tHash.indexOf('&') > -1) {
		var recoverParams = tHash.split("&"); // split the hash by &
		var originalHash = recoverParams[0]; // save this as a fallback for what the hash should be post clean up
		/** Loop through the split hash and look for URL parameters that we will then add back to the URL */
		recoverParams.forEach(function(p) {
			if (p.indexOf("#") == -1) { // If # is not present then it is likely a URL parameter
				var keyValue = p.split("="); // split by = just in case it is not 
				if (keyValue.length == 2) { tParams.set(keyValue[0], keyValue[1]); } // If the length is 2 then we know we got a key/value pair and we can add it back to the parameters
			} else { originalHash = p; } // # is present - this is what the hash should be post clean up
		});
		tURL.hash = originalHash;
		window.history.replaceState({}, '', tURL.href); // replace URL with cleaned up version
	}

	/** _zm_cms_guid cookie code */
	var otCookies = checkCookie("OptanonConsent");
	if (logging == true) {
		console.log("Current URL is "+window.location.href);
	}
	if (otCookies == null) { otCookies = ""; }
	var cmsCookie = checkCookie("_zm_cms_guid");
	if (logging == true) {
		console.log("cms cookie value = "+cmsCookie);
	}

	/** Check to see if third party cookies are disabled in Chrome */
	var tpcd = true;
	var iframe_url = "https://www.zoom.us/third_party_cookie_check.html";
	if (window.location.href.indexOf('zoomus') > -1) { iframe_url = "https://dev-integration.zoomdev.us/third_party_cookie_check.html"; }
	//if (window.location.href.indexOf('support.zoom.com') > -1 || window.location.href.indexOf('zoomus.service-now.com') > -1) { iframe_url = "https://www.zoom.us/third_party_cookie_check.html";}
	if (isChrome()) {
		// Have we already checked third party cookies today? 
		var tpcd_cookie = checkCookie("_zm_tpcd_checked");
		// If tpde_cookie is null then we have not checked and we need to create the iframe to check Chrome's third party cookies 
		if (tpcd_cookie == null) {
			if (window.location.href.indexOf('support.zoom.com') > -1) { tpcd = await isThirdPartyCookieDisabled(3000, iframe_url); } // only run on prod for now - change this if needing to test
			// Set cookie to show that we have already checked this, value will show (inverse) whether or not third party cookies are enabled
			if (window.location.href.indexOf('zoomusdev') > -1) { document.cookie = "_zm_tpcd_checked=" + tpcd.toString() + "; " + (24* 60 * 60 * 1000) + "; path=/";}
			else { document.cookie = "_zm_tpcd_checked=" + tpcd.toString() + "; " + (24* 60 * 60 * 1000) + "; domain=zoom.com; path=/"; }
		} 
		// We already checked - we can pull the value from tpcd_cookie value
		else {
			if (tpcd_cookie == "false") { tpcd = false; }
			else if (tpcd_cookie == "true") { tpcd = true; }
		}
		// tpcd = true means disabled, tpcd = false means enabled 
	}
	
	/** CHROME with third party cookies enabled - DON'T NEED TO DO ANYTHING HERE */
	if ((isChrome() || isCrawler()) && !tpcd ) {
		if (logging == true) {
			console.log("Browser is Chrome based with third party cookies enabled or is a crawler, don't need to check for cookie");
		}
	}
	/** DONT NEED TO DO ANYTHING FOR CONTENT ONLY URL */
	else if (params.onlycontent != undefined) {
		if (logging == true) {
			console.log("onlycontent URL parameter present - dont need cookie logic");
		}
	}
	/** NON-CHROME + WE RECEIVE cms_guid URL PARAMETER - NEED TO SET COOKIE HERE */
	else if (params.cms_guid != undefined && cmsCookie == null) {
		// Determine cookie expiration date.
		// If cms_guid == "false" then we set the cookie for 1hr. Otherwise set for 24hr.
		var expireTime;
		if (params.cms_guid == "false" || params.cms_guid == false) { expireTime = 60 * 60 * 1000;}
		else { expireTime = 24* 60 * 60 * 1000; }
		
		// Set Cookie on zoom.com domain
		var date = new Date();
		date.setTime(date.getTime() + expireTime); // 1 hour in milliseconds
		var expires = "expires=" + date.toUTCString();
		
		// Set different cookies for prod/dev
		if (window.location.href.indexOf('zoomusdev') > -1) { document.cookie = "_zm_cms_guid=" + params.cms_guid + "; " + expires + "; path=/";}
		else { document.cookie = "_zm_cms_guid=" + params.cms_guid + "; " + expires + "; domain=zoom.com; path=/"; }
		
		// Clean up URL by removing cms_guid and lang parameters
		var url = new URL(window.location.href);
		var searchParams = new URLSearchParams(url.search);
		searchParams.delete("cms_guid");
		if (params.logged_in != undefined) { searchParams.delete("logged_in");}
		if (params.lang != undefined) { searchParams.delete("lang"); }
		url.search = searchParams.toString();
		if (logging == true) { console.log("Cleaning current URL to "+url); }
		window.history.replaceState({}, '', url);
	}
	/** NON-CHROME + cms_guid URL PARAMETER IS NOT PRESENT. NEED TO DETERMINE WHETHER OR NOT TO GO GET IT. */
	else {
		if (logging == true) { console.log("Browser is not Chrome based - cookie value is "+cmsCookie); }
		/** _zm_cms_guid cookie does not exist at all so we need to redirect to syncStatus */
		if (cmsCookie == null) {
			// Determine which URL to redirect to
			var newURL = "";
			if (window.location.href.indexOf('zoomusdev') > -1) { newURL = "https://dev-integration.zoomdev.us/syncStatus?continue=https://zoomusdev.service-now.com/hc?id=contact_us"; }
			else { newURL = "https://zoom.us/syncStatus?continue="+encodeURIComponent(window.location.href);}
			//window.location.replace(newURL); // Redirect
			if (window.location.href.indexOf('support.zoom.com') > -1) {
				window.location.replace(newURL); // Redirect
			} else { console.log("Would be redirecting to : "+newURL); }
		}
		/** Cookie already exists as "false" but we have a URL parameter indicating that the user logged in via the bot -- Need to get an updated cookie value. */
		else if (cmsCookie == "false" && params.logged_in=="true") {
			// Dev
			if (window.location.href.indexOf('zoomusdev') > -1) { 
				document.cookie = "_zm_cms_guid=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; // Clear cookie
				window.location.replace("https://dev-integration.zoomdev.us/syncStatus?continue=https://zoomusdev.service-now.com/hc"); // Redirect
			}
			// Prod
			else { 
				document.cookie = "_zm_cms_guid=; expires=Thu, 01 Jan 1970 00:00:00 UTC; domain=zoom.com; path=/;"; // Clear cookie
				window.location.replace("https://zoom.us/syncStatus?continue="+encodeURIComponent(window.location.href)); // Redirect
			}
		}
		/** Cookie already exists and is set properly. Don't need to do anything here. */
		else {
			if (window.location.href.indexOf('zoomus') >-1) { console.log("Cookie exists and is not 'false' - no redirect"); }
		}
		if (params.logged_in != undefined) {
			var url = new URL(window.location.href);
			var searchParams = new URLSearchParams(url.search);
			searchParams.delete("logged_in");
		}
	}
	/** end cookie code */

	if (params.onlycontent=='1') {
		$('html').addClass('contentonly');
	}
	else {
		params.onlycontent='0';
	}

	if (params.nohyperlink=='1') {
		$('html').addClass('nohyperlink');
		$('.kb-article-content a').each(function(e) {
			console.log(e);
			/***
				Cases where we just replace the parameters for the link :
				- support.zoom.us is found in the link
				- /articles/ is found in the link
				- /requests is not found in the link
			***/
			if ($(this).attr('href').indexOf('support.zoom.us') > -1  && $(this).attr('href').indexOf('/articles/') > -1 && $(this).attr('href').indexOf('/requests') == -1) {
				var tmp = $(this).attr('href');	
				if ($(this).attr('href').indexOf('#') > -1) {	
					var url_split = tmp.split("#");	
					var new_url = url_split[0] + '?onlycontent='+params.onlycontent+'&nohyperlink='+params.nohyperlink + '#' + url_split[1];	
					$(this).attr('href', new_url);	
				}	
				else {	
					$(this).attr('href', tmp + '?onlycontent='+params.onlycontent+'&nohyperlink='+params.nohyperlink);	
				}
			}
			/***
				Cases where we do nothing with the link (either): 
				- the data-toggle property = collapse (accordion link)
				- the first character of the link is a # and https is not found (anchor link)
			***/
			else if ($(this).data('toggle') == 'collapse' || ($(this).attr('href').charAt(0) == "#" && $(this).attr('href').indexOf('https:') == -1)) {
				//do nothing
			}
			// All other links we just remove
			else {
				$(this).addClass('dead-link');
				$(this).removeAttr("href");
			}
		});
  }
	
}

// Loads a script and then runs the callback function
function loadScript( url, callback ) {
  var script = document.createElement( "script" )
  script.type = "text/javascript";
  if(script.readyState) {  // only required for IE <9
    script.onreadystatechange = function() {
      if ( script.readyState === "loaded" || script.readyState === "complete" ) {
        script.onreadystatechange = null;
        callback();
      }
    };
  } else {  //Others
    script.onload = function() {
      callback();
    };
  }

  script.src = url;
  document.getElementsByTagName( "head" )[0].appendChild( script );
}

function getQueryParams (queryString)
{
	queryString = queryString.split ('+').join (' ');

	var params = {};
	var tokens;
	var regex = /[?&]?([^=]+)=([^&]*)/g;

	while (tokens = regex.exec (queryString))
	{
	params[decodeURIComponent (tokens[1])] = decodeURIComponent (tokens[2]);
	}

	return params;
}

function isChrome() {
	return navigator.userAgent.toLowerCase().includes("chrome");
}

function isCrawler() {
	var botPattern = "(googlebot\/|bot|Googlebot-Mobile|Googlebot-Image|Google favicon|Mediapartners-Google|bingbot|slurp|java|wget|curl|Commons-HttpClient|Python-urllib|libwww|httpunit|nutch|phpcrawl|msnbot|jyxobot|FAST-WebCrawler|FAST Enterprise Crawler|biglotron|teoma|convera|seekbot|gigablast|exabot|ngbot|ia_archiver|GingerCrawler|webmon |httrack|webcrawler|grub.org|UsineNouvelleCrawler|antibot|netresearchserver|speedy|fluffy|bibnum.bnf|findlink|msrbot|panscient|yacybot|AISearchBot|IOI|ips-agent|tagoobot|MJ12bot|dotbot|woriobot|yanga|buzzbot|mlbot|yandexbot|purebot|Linguee Bot|Voyager|CyberPatrol|voilabot|baiduspider|citeseerxbot|spbot|twengabot|postrank|turnitinbot|scribdbot|page2rss|sitebot|linkdex|Adidxbot|blekkobot|ezooms|dotbot|Mail.RU_Bot|discobot|heritrix|findthatfile|europarchive.org|NerdByNature.Bot|sistrix crawler|ahrefsbot|Aboundex|domaincrawler|wbsearchbot|summify|ccbot|edisterbot|seznambot|ec2linkfinder|gslfbot|aihitbot|intelium_bot|facebookexternalhit|yeti|RetrevoPageAnalyzer|lb-spider|sogou|lssbot|careerbot|wotbox|wocbot|ichiro|DuckDuckBot|lssrocketcrawler|drupact|webcompanycrawler|acoonbot|openindexspider|gnam gnam spider|web-archive-net.com.bot|backlinkcrawler|coccoc|integromedb|content crawler spider|toplistbot|seokicks-robot|it2media-domain-crawler|ip-web-crawler.com|siteexplorer.info|elisabot|proximic|changedetection|blexbot|arabot|WeSEE:Search|niki-bot|CrystalSemanticsBot|rogerbot|360Spider|psbot|InterfaxScanBot|Lipperhey SEO Service|CC Metadata Scaper|g00g1e.net|GrapeshotCrawler|urlappendbot|brainobot|fr-crawler|binlar|SimpleCrawler|Livelapbot|Twitterbot|cXensebot|smtbot|bnf.fr_bot|A6-Indexer|ADmantX|Facebot|Twitterbot|OrangeBot|memorybot|AdvBot|MegaIndex|SemanticScholarBot|ltx71|nerdybot|xovibot|BUbiNG|Qwantify|archive.org_bot|Applebot|TweetmemeBot|crawler4j|findxbot|SemrushBot|yoozBot|lipperhey|y!j-asr|Domain Re-Animator Bot|AddThis)";
	var re = new RegExp(botPattern, 'i');
	var userAgent = navigator.userAgent; 
	return re.test(userAgent);
}

async function isThirdPartyCookieDisabled(timeoutMs, url) {
	return new Promise((resolve) => {
	  const iframe = document.createElement('iframe');
	  const targetOrigin = url;
	  let resolved = false;
  
	  iframe.style.display = 'none';
	  iframe.src = targetOrigin;
  
	  const timeout = setTimeout(() => {
		if (!resolved) {
		  resolved = true;
		  iframe.remove();
		  resolve(true); // Assume cookies are disabled on timeout
		}
	  }, timeoutMs);
  
	  iframe.onload = () => {
		try {
			iframe.contentWindow.postMessage({ type: 'checkCookies' }, targetOrigin);
		} catch (e) {
		  	clearTimeout(timeout);
		  	resolved = true;
		  	iframe.remove();
		  	resolve(true); // Assume disabled if postMessage fails
		}
	  };
  
	  function handleMessage(event) {
		//if ((event.origin === "https://dev-integration.zoomdev.us" || event.origin === "https://zoom.us") && event.source === iframe.contentWindow && event.data.type === 'cookieStatus') {
		if (event.data.type === 'cookieStatus') {
			if (logging == true) {console.log("This message met the criteria.", event);}
			clearTimeout(timeout);
			resolved = true;
			window.removeEventListener('message', handleMessage);
			iframe.remove();
			resolve(!event.data.status); // Invert: true means disabled
		}
	  }
  
	  window.addEventListener('message', handleMessage);
	  document.body.appendChild(iframe);
	});
}

// GTM
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-P49W6ZT');

// GTM Meta tag
(function() {
    var meta = document.createElement('meta');
    meta.content = "kG0lrfAGd5hMPBIAGI_0WUl7kfnMfkbV0udmarblZ-0";
    meta.name = "google-site-verification";
    document.getElementsByTagName('head')[0].appendChild(meta);
})();

// Map Invalid Language Codes
(function() {
    var mainTag = document.getElementsByTagName('html')[0];
    try {
        if(mainTag.getAttribute("lang") == "pb") {
            mainTag.setAttribute("lang", "pt-BR");
        }
		if(mainTag.getAttribute("lang") == "zh") {
			mainTag.setAttribute("lang","zh-CN");
		}
		if (mainTag.getAttribute("lang") == "zt") {
			mainTag.setAttribute("lang","zh-TW");
		}
    }
    catch(e) {
 	    console.error(e.message);
    }
})();

// Load in OneTrust
(function() {

	var urlParams = new URLSearchParams(window.location.search);
	var joeyTest = urlParams.get('onetrust-test-id');
    var top = document.querySelector('head'); // reach out to the parent window and get the head element
    var script = document.createElement('script'); //create a new script element
    script.src = 'https://cdn.cookielaw.org/scripttemplates/otSDKStub.js'; //sets the src attribute
    script.type = 'text/javascript'; //sets the type attribute
	script.charset = 'UTF-8';
	if (joeyTest == "true" || joeyTest == true) {
		script.setAttribute('data-domain-script', '054bb50c-9aa4-49a0-8c41-57b963195b3a');
	}
	else if (window.location.href.indexOf('zoomusdev') > -1) { 
		script.setAttribute('data-domain-script', 'aba09413-cfa0-4804-93ab-728d23c230df'); }
	else if (window.location.href.indexOf('zoomustest') >-1) {
		script.setAttribute('data-domain-script', 'e7e20584-b074-4102-83e9-77e06e202287');
	}
	else {
		script.setAttribute('data-domain-script', '054bb50c-9aa4-49a0-8c41-57b963195b3a');
	}
    script.id = 'onetrust-script';
	top.appendChild(script); // appends the newly created script element at the end of the top window head element
})();

function getMobileOperatingSystem() {
  var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  // Windows Phone must come first because its UA also contains "Android"
  if (/windows phone/i.test(userAgent)) {
    return "Windows Phone";
  }
  if (/android/i.test(userAgent)) {
    return "Android";
  }
  if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
    return "iOS";
  }
  return "unknown";
}

function handleArticleOnload() {
	
	/*This mutation observer can be used to action on items that may load in via widgets*/
	var bodyNode = document.getElementsByTagName('body')[0];
	var config = { attributes: false, childList:true, subtree: true };
	var callback = function(mutationList, observer) {
		//console.log("in callback");
		if ($('.youtube-player').length > 0 && $('.kb-article-wrapper').length > 0) {
			if (logging == true) { console.log("initializing youtube video from mutationobvserver callback function"); }
			initYouTubeVideos();
			//QSI.run();
			observer.disconnect();
		}
		else if ($('.kb-article-wrapper').length > 0 || $('.kb-article-wrapper a').length > 0) {

			observer.disconnect();
		}

		/* Gather OS Info For Smart Sort & Auto Expand */
		var OSName="Unknown OS";
		if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
		if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";
		if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
		if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";
		var mobileOSName = getMobileOperatingSystem();
		if (mobileOSName == 'Android') OSName="Android";
		else if (mobileOSName == 'iOS') OSName="iOS";

		var accordions;
		if(OSName == "Windows"){
			accordions = $('.panelMacPC, .panelPC, .panelMacPCLinux, .panelPCAll');
		}
		else if(OSName == "MacOS"){
			accordions = $('.panelMacPC, .panelMac, .panelMacPCLinux');
		}
		else if(OSName == "UNIX" || OSName == "Linux"){
			accordions = $('.panelMacPCLinux, .panelLinux');
		}
		else if(OSName == "iOS"){
			accordions = $('.panelIOSAndroid, .panelIOS');
		}
		else if(OSName == "Android"){
			accordions = $('.panelIOSAndroid, .panelAndroid');
		}
		else {
			accordions = $('.kb-article-content .panel').first();
		}

		$(accordions).each(function() {
			var alink = $(this).find('.panel-heading > .panel-title a').first();
			var content = $(this).find('.panel-collapse').first();
			$(alink).removeClass('collapsed').attr('aria-expanded', true);
			$(content).addClass('in').attr('aria-expanded', true);
		});

		if (window.location.href.indexOf('#') == -1) {
			$('html').animate({ scrollTop: $('html').offset().top}, 0);
		}

	};
	// Create an observer instance linked to the callback function
	var observer = new MutationObserver(callback);

	// Start observing the target node for configured mutations
	observer.observe(bodyNode, config);
}

function handleCategoryOnload() {
	
	/*This mutation observer can be used to action on items that may load in via widgets*/
	var bodyNode = document.getElementsByTagName('body')[0];
	var config = { attributes: false, childList:true, subtree: true };
	var callback = function(mutationList, observer) {
		if ($('.youtube-player').length > 0 && $('.product-video-box').length > 0) {
			//console.log("initializing youtube video from mutationobvserver callback function");
			initYouTubeVideos();
			//QSI.run();
			observer.disconnect();
		}
		else if ($('.product-video-box').length > 0) {
			observer.disconnect();
		}
	};
	// Create an observer instance linked to the callback function
	var observer = new MutationObserver(callback);

	// Start observing the target node for configured mutations
	observer.observe(bodyNode, config);
}

function setQualtricsVariables(locale, oac, name, email, role, id) {
	qualtrics_locale = locale;
	isOAC = oac;
	user_name = name;
	user_email = email;
	user_role = role;
	article_id = id;
	if (logging == true) { console.log("Setting Qualtrics Variables : ", qualtrics_locale, isOAC, user_name, user_email, user_role, article_id); }
}

function formatDigitalCSHeader(mobile) {
	// Standard
	if (!mobile) {
		$('#cs-header').removeClass('mobile');
		$('.header-search-container').insertAfter('#header-mainbar > ul');
	}
	// Mobile
	else {
		$('#cs-header').addClass('mobile');
		$('.header-search-container').appendTo('.search-container-mobile');
	}
}

function openChatbot() {

	if (logging == true) { console.log("Open Chatbot Function"); }
	if (window.location.href.indexOf('zva_test=1') > -1 || logging == true) {
		console.log(zoomCampaignSdk);
	}

	try {
		var campaignId = zoomCampaignSdk.campaigns[0].name;
		if (campaignId == "lazyLoadCampaign") {
			$('.livesdk__invitation')[0].click();
			openedChatbot = true;
		}
		else {
			zoomCampaignSdk.open();
			openedChatbot = true;
		}
	} catch(error) {
		if ($('.livesdk__invitation').length > 0 && ($('#onetrust-banner-sdk').length == 0)) {
			$('.livesdk__invitation')[0].click();
			openedChatbot = true;
		}
		else {
			checkAndClickElement('.livesdk__invitation', 5);
		}
	}	
}

function checkAndClickElement(selector, maxAttempts) {
  let attempts = 0;
  
  const interval = setInterval(() => {
    attempts++;
    if ($(selector).length > 0 && ($('#onetrust-banner-sdk').length == 0) || ($('#onetrust-banner-sdk').css('display') == 'none')) {
      if ($(selector)[0] != undefined) {
		$(selector)[0].click();
		openedChatbot = true;
		clearInterval(interval);
	  }
    } else if (attempts >= maxAttempts) {
      clearInterval(interval);
    }
  }, 500);
}

// Function that hides/shows navbar elements based on remaining width. Runs on page load and whenever the page is resized. 
function checkSupportBarWidth() {
	//console.log("Checking Support Bar width - Recursive Call "+supportRecursiveCalls);
    if (window.innerWidth > 768) {
        contactSupportWidth = $('#header-support-ul').children().last().width();
    }

    // Prevent this function from running more than twice in a row.
    if (supportRecursiveCalls > 1) {
        supportRecursiveCalls = 0;
        return;
    }

    // The difference in width between the UL that holds our links + the Coveo Search component and the width of the overall bar. 
	var supportBarWidth = 0;
	$('#header-support-ul').children().each(function(e) {
		supportBarWidth += $(this).width();
	});
	var totalBarWidth = $('#header-support > .header-container').width();
	var searchContainerWidth = $('.header-search-container').width();

    var widthDiff = totalBarWidth - (supportBarWidth + searchContainerWidth);
	//console.log(totalBarWidth, searchContainerWidth, widthDiff);

    // If there is negative width left (overlapping) then we find the last li that does not have the .invisible class and we add the .invisible class. 
    // Then, rerun the function to check whether or not we are still overlapping.
    if (widthDiff <= 120) {
        //$('#header-support-ul').find('li:not(.invisible):last').addClass('invisible');
        //supportRecursiveCalls++;
        //checkSupportBarWidth();
        $('#contact-support-li').appendTo($('#more-support-dropdown'));
    } else {
		$('#contact-support-li').appendTo($('#header-support-ul'));
		//supportRecursiveCalls++;
        //checkSupportBarWidth();
	}
}

// Function that checks the main bar's width in the nav and switches to hamburger menu when applicable
function checkMainBarWidth(shrinking, widening, onload) {

    // Return if we're already on mobile and we're shrinking or we're already on desktop and we're widening. 
    if ($('#header-mainbar').hasClass('smaller-mobile-size') && shrinking == true) {
        return;
    }
    if (!$('#header-mainbar').hasClass('mobile-size') && widening == true) {
        return;
    }

    // Prevent this function from running more than twice in a row.
    if (recursiveCalls > 1) {
        recursiveCalls = 0;
        return;
    }

    // TABLET CHECK
    // Dont run this code if we are already on mobile - no point
    if (!$('#header-mainbar').hasClass('smaller-mobile-size')) {

        var widthDiff = $('#header-mainbar').width() - ($('#main-menubar').outerWidth(true) + $('#join-host-bar').outerWidth(false) + $('#header-logo-a').outerWidth(true) + 120);
		//console.log(widthDiff, !$('#header-mainbar').hasClass('mobile-size'));

        if (widthDiff >= 0 && !$('#header-mainbar').hasClass('mobile-size') && tabletBreakpointSet == false) {
            tabletBreakpoint = $('#main-menubar').outerWidth(true) + $('#join-host-bar').outerWidth(false) + $('#header-logo-a').outerWidth(true) + 120;
			if (tabletBreakpoint <= 1023) { tabletBreakpoint = 1024; }
            tabletBreakpointSet = true;
			//console.log("Setting tablet breakpoint to " + tabletBreakpoint);
        }
        if (((widthDiff <= 0) && !$('#header-mainbar').hasClass('mobile-size')) || 
		(window.innerWidth < tabletBreakpoint && !$('#header-mainbar').hasClass('mobile-size'))) {
			//console.log("adding mobile-size");
            $('#header-mainbar').addClass('mobile-size');
			$('#header-support').addClass('mobile-sub');
            $('.header .active-dropdown').removeClass('active-dropdown');
            $('#my-account-li').appendTo('#main-menubar');
			//console.log($('#my-account-li'), $('#main-menubar'));
            $('#sign-in-li').appendTo('#main-menubar');
            $('.bottom-button > ul a').attr('tabindex', '-1');
        }

        else if (window.innerWidth > tabletBreakpoint && $('#header-mainbar').hasClass('mobile-size')) {
			//console.log(window.innerWidth, tabletBreakpoint, "removing mobile-size");
			if ($('#main-nav-checkbox').prop('checked') == true) {
				$('#main-nav-checkbox-label').click();
			}
			$('#header-support').css('visibility', 'visible');
			$('.header-search-container .FlyoutButton').css('visibility', 'visible');
			$('.body').css('visibility', 'visible');
			$('footer').css('visibility', 'visible');
            $('#header-mainbar').removeClass('mobile-size');
			$('#header-support').removeClass('mobile-sub');
            $('#my-account-li').appendTo('#join-host-bar');
            $('#sign-in-li').appendTo('#join-host-bar');
            $('.bottom-button > ul a').attr('tabindex', '0');
            $('#main-menubar').removeClass('show-dropdown');
            $('.header .active-dropdown').removeClass('active-dropdown');
        }
    }

    // MOBILE CHECK
    if ($('#header-mainbar').hasClass('mobile-size')) {
		//console.log("Mobile check");
        var mobileWidthDiff = $('#header-mainbar > .header-container').width() - ($('#header-logo-a').outerWidth(true) + $('#join-host-bar').outerWidth(false) + $('#main-nav-checkbox-label').width() + 120);

        if (mobileWidthDiff >= 0 && !$('#header-mainbar').hasClass('smaller-mobile-size') && mobileBreakpointSet == false) {
            mobileBreakpoint = $('#header-logo-a').outerWidth(true) + $('#join-host-bar').outerWidth(false) + $('#main-nav-checkbox-label').width() + 120;
            mobileBreakpointSet = true;
			if (mobileBreakpoint < 481) { mobileBreakpoint = 481; }
			//console.log("mobile breakpoint set to ", mobileBreakpoint);
        }

        if (window.innerWidth < mobileBreakpoint && !$('#header-mainbar').hasClass('smaller-mobile-size')) {
			//console.log("adding smaller-mobile-size class");
            $('#header-mainbar').addClass('smaller-mobile-size');
			$('#header-support').addClass('smaller-mobile-sub');
            $('#join-li').appendTo('#main-menubar');
            $('#host-li').appendTo('#main-menubar');
        }

        if (window.innerWidth > mobileBreakpoint && $('#header-mainbar').hasClass('smaller-mobile-size')) {
			//console.log("removing smaller-mobile-size class");
            $('#header-mainbar').removeClass('smaller-mobile-size');
			$('#header-support').removeClass('smaller-mobile-sub');
            $('#host-li').prependTo('#join-host-bar');
            $('#join-li').prependTo('#join-host-bar');

            // This is a specific case where we are jumping straight from mobile to desktop while skipping tablet. We need to rerun the function 1 time to fix the bar, otherwise it still has the 'mobile-size' class.
            if (window.innerWidth > tabletBreakpoint) {
                setTimeout(function() {
                    recursiveCalls++;
                    checkMainBarWidth(false, true, true);
                }, 500);
            }
        }
    }
}

// Code to handle Youtube lazy load
/*
 * Light YouTube Embeds by @labnol
 * Credit: https://www.labnol.org/
 */
function labnolIframe(div) {
    var iframe = document.createElement('iframe');
    iframe.setAttribute(
        'src',
        'https://www.youtube-nocookie.com/embed/' + div.dataset.id + '?autoplay=1&rel=0'
    );
    iframe.setAttribute('frameborder', '0');
    iframe.setAttribute('allowfullscreen', '1');
	iframe.setAttribute('referrerpolicy','strict-origin-when-cross-origin');
	//iframe.setAttribute('title','YouTube video player');
    iframe.setAttribute(
        'allow',
        'accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture; web-share'
    );
    div.parentNode.replaceChild(iframe, div);
}

function initYouTubeVideos() {
	formatTopPadding();
	if (logging == true) { console.log("Initializing Youtube Videos"); }
    // Check to see if functional cookies are enabled
	if (activeCookies == null) { activeCookies = "";}
    if (activeCookies.indexOf('C0003%3A1') > -1 || activeCookies.indexOf('C0003:1') > -1) {
    //if (activeCookies) {
        $('.youtube-player').css('height', '0');
        $('.youtube-player').css('padding-bottom', '56.25%');
        $('.slider-item').css('aspect-ratio', '16/9');
        $('.youtube-player').html('');
		$('.youtube-player').removeClass('cookie-error');
        var playerElements = document.getElementsByClassName('youtube-player');
        for (var n = 0; n < playerElements.length; n++) {
			//console.log(playerElements[n]);
            var videoId = playerElements[n].dataset.id;
            var div = document.createElement('div');
            div.setAttribute('data-id', videoId);
            div.setAttribute('tabIndex', '0');
            var thumbNode = document.createElement('img');
            thumbNode.src = '//i.ytimg.com/vi/ID/hqdefault.jpg'.replace(
                'ID',
                videoId
            );
            div.appendChild(thumbNode);
            var playButton = document.createElement('div');
            playButton.setAttribute('class', 'play');
            div.appendChild(playButton);
            div.onclick = function() {
                labnolIframe(this);
            };
            div.onkeypress = function(e) {
                if (e.keyCode == 13) {
                    labnolIframe(this);
                }
            };
            playerElements[n].appendChild(div);
        }
        modifySliderVideos();
    } else {
        $('.slider-item').css('aspect-ratio', 'initial');
        $('.youtube-player').css('height', 'initial');
        $('.youtube-player').css('padding-bottom', '0');
        $('.youtube-player').html('<p></p>');
		$('.youtube-player').addClass('cookie-error');
    }
}

// If on a page with a carousel then youtube videos could be embedded in a slider-item div, which also has a tabindex. We want to keep that tabindex so that the slider functions properly, but we want to add a function when the user presses Enter so that the video inside of the slider element plays. 
function modifySliderVideos() {
    if ($('.video-box').length > 0) {
        $('.slider-item .youtube-player > div').attr('tabindex', '-1');
        $('.slider-item').bind('click keypress', function(e) {
            if ((e.type == 'keypress' && e.which == 13)) {
                labnolIframe($(this).find('.youtube-player > div')[0]);
            }
        });
    }
}

function scrollUp() {
	if (window.location.href.indexOf('#') == -1) {
		$('html').animate({ scrollTop: $('html').offset().top}, 0);
	}
}

function onResize() {
    w = window.innerWidth;
    h = window.innerHeight;
    calls += 1;
    c = calls;

	if (old_width < 768 && window.innerWidth >= 768 && ($('#support-nav-checkbox').prop('checked') == true)) {
		$('#support-nav-checkbox').click();
	}

	// Digital CSM Header mobile view
	//console.log(old_width, window.innerWidth, $('#mainbar-checkbox').prop('checked'));
	if (old_width < 1024 && window.innerWidth >= 1024) {
		if ($('#mainbar-checkbox').prop('checked') == true) { $('#mainbar-checkbox').click(); }
		formatDigitalCSHeader(false);
	}
	else if (old_width >= 1024 && window.innerWidth < 1024) {
		if ($('#mainbar-checkbox').prop('checked') == true) { $('#mainbar-checkbox').click(); }
		formatDigitalCSHeader(true);
	}
	else if (old_width == 0 && window.innerWidth < 1024) {
		formatDigitalCSHeader(true);
	}

	// end digital CSM header mobile code

    // Code goes here
    // If window goes from monitor size to tablet size we hide any dropdowns that were open on the monitor window and we remove the slider functionality from video tutorials
    if (window.innerWidth < 1024 && old_width >= 1024) {
        if ($('.video-box').length > 0) {
            $('.youtube-player').empty();
            initYouTubeVideos();
            $('.video-box').slick('unslick');
        }

    }
    // If window goes from tablet size to monitor size and we are on the homepage then we restore the video tutorials slider functionality
    else if (window.innerWidth >= 1024 && $('#video-box').hasClass('slick-initialized') == false) {
        if ($('.video-box').length > 0) {
            $('.youtube-player').empty();
            initYouTubeVideos();
            $('#video-box').slick({
                infinite: true,
                slidesToShow: 3,
                slidesToScroll: 3,
                arrows: true,
                adaptiveHeight: true,
                responsive: [{
                    breakpoint: 1024,
                    settings: "unslick"
                }]
            });
        }
    }

    // Set top padding
    var headerHeight = '114px';
	csHeaderHeight = '57px';
	var footerHeight = '512px';
    try {
		if (document.querySelectorAll('#header-main-container').length > 0) {
			headerHeight = document.querySelectorAll('#header-main-container')[0].offsetHeight + 'px';
		}
		if (document.querySelectorAll('.footer').length > 0) {
			footerHeight = document.querySelectorAll('.footer')[0].offsetHeight;
		}
		if (document.querySelectorAll('#cs-header').length > 0) {
			csHeaderHeight = document.querySelectorAll('#cs-header')[0].offsetHeight + 'px';
		}
    } catch (error) {
		console.log(error);
	}
    
	if (window.location.href.indexOf('.com/cs') > -1) { 
		document.querySelectorAll('body')[0].style.paddingTop = csHeaderHeight;
	}
	else { document.querySelectorAll('body')[0].style.paddingTop = headerHeight; }

    //
    old_width = w;
    old_height = h;

	formatTopPadding();

	if (window.innerWidth > old_width) {
		checkMainBarWidth(false, true, false);
		checkSupportBarWidth(false, true);
	} else if (window.innerWidth < old_width) {
		checkMainBarWidth(true, false, false);
		checkSupportBarWidth(true, false);
	} else {
		checkMainBarWidth(false, false, true);
		checkSupportBarWidth(false, false);
	}
	
	// If we're on tablet size move Contact Us into the Support dropdown
	if (window.innerWidth <= 768 && $('#header-support-ul').children().length < 4) {
		$('#contact-support-li').appendTo($('#header-support-ul'));
	}

	changeResourcesText();

	old_width = window.innerWidth;
}

/* Formatting functions for resizing the header
 * formatTopPadding()
 * changeResourcesText()
 * checkSupportBarWidth()
 * checkMainBarWidth()
 */
function formatTopPadding() {
    // Reset header min-height
	if (window.location.href.indexOf('.com/cs') > -1) { 
		//document.querySelectorAll('body')[0].style.paddingTop = csHeaderHeight;
		$('.cs-header').css('min-height','initial');
		$('body').css('padding-top', $('.cs-header').height());
		$('html').css('scroll-padding-top', $('.cs-header').height() + 10);
		return;
	}
    $('.header').css('min-height', 'initial');

    $('body').css('padding-top', $('.header').height());
    //$('.header').css('min-height', $('.header').height());
    $('html').css('scroll-padding-top', $('.header').height() + 10);
}

function changeResourcesText() {
    if (window.innerWidth > 768) {
        $('#resources-dropdown .dropdown-footer-inner .inner1 .inner-txt a').text("Download Center");
        $('#resources-dropdown .dropdown-footer-inner .inner2 .inner-txt a').text("Browse Backgrounds");
    } else {
        $('#resources-dropdown .dropdown-footer-inner .inner1 .inner-txt a').text("Download Zoom Client");
        $('#resources-dropdown .dropdown-footer-inner .inner2 .inner-txt a').text("Zoom Virtual Backgrounds");
    }
}

// Set a Cookie
function setCookie(cName, cValue, expDays) {
	var date = new Date();
	date.setTime(date.getTime() + (expDays * 24 * 60 * 60 * 1000));
	var expires = "expires=" + date.toUTCString();
	document.cookie = cName + "=" + cValue + "; " + expires + "; path=/";
	if (logging == true) { console.log("Setting Cookie : ", cName, cValue, expDays); }
}

// Check a Cookie Value
function checkCookie(name) {
	var match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
	if (logging == true) { console.log("Checking Cookie : ", name, match); }
	if (match) { return match[2]; }
	else { return null; }
}

// Creates an empty cookie based on the number of sections/cards on this page
function createStructure() {

	var structure = {};
	var number_of_sections = $('.gs-card-section .cards-container').length;	
	for (var x=0; x<number_of_sections; x++) {
		
		var cards_container = $('.gs-card-section .cards-container')[x];
		var number_of_cards = $(cards_container).find('.gs-card').length;
		
		structure[x] = new Array(number_of_cards).fill(0);
		
	}

	return JSON.stringify(structure);
}

// For the Getting Started Pages - removes the Unread tag from all tiles. Used when someone disables cookies
function removeUnread() {
	$('.gs-cards .unread').removeClass('unread');
}

/** Disable / Enable Coveo Analytics based on cookie preferences **/
function coveoAnalytics() {
	activeCookies = checkCookie("OptanonConsent");
	var root = document.querySelector('.CoveoSearchInterface');
	// Check to see if targeting cookies are enabled
	if (activeCookies == null) {
		if (logging == true) { console.log("Disable Coveo Analytics until we have active cookie value"); }
		Coveo.disableAnalytics(root);
	}
	else if (activeCookies.indexOf('C0004%3A1') > -1 || activeCookies.indexOf('C0004:1') > -1) { 
		if (logging == true) { console.log("Enable Coveo Analytics"); }
		Coveo.enableAnalytics(root);
	}
	else {
		if (logging == true) { console.log("Disable Coveo Analytics"); }
		Coveo.disableAnalytics(root);
	} 
}

function setTargetingVariable() {
  activeCookies = checkCookie("OptanonConsent");

  if (activeCookies == null) { 
	  targeting_enabled = false; 
  }
  else if (activeCookies.indexOf('C0004%3A1') > -1 || activeCookies.indexOf('C0004:1') > -1) { 
    targeting_enabled = true;
    if (window.location.href.indexOf('_guide') > -1) {
      	var event = new Event("cookie_update");
		var elem = document.querySelector('head');
		elem.dispatchEvent(event);
    }

	else { 
		var event = new Event("onetrust_update");
		var elem = document.querySelector('head');
		elem.dispatchEvent(event);
	}

  }
  else {
    targeting_enabled = false;
    if (window.location.href.indexOf('_guide') > -1) {
      removeUnread();
    }

	else { 
		var event = new Event("onetrust_update");
		var elem = document.querySelector('head');
		elem.dispatchEvent(event);
	}
  }
  targeting_set = true;

}

function accordionToggle() {
		
	$('body').on('click', '.accordion-btn', function(e) {
		$control = $(this);

		// Get ID of div that this controls from the ID of this
		// ie. #accordion-control-div1 controls #div1
		accordionContentID = $(this).attr('id').replace("accordion-control-","#");
		accordionContent = $(accordionContentID);

		if ($(accordionContent).hasClass('open')) {
			$(accordionContent).attr('aria-hidden', 'false'); 
			$(this).attr('aria-expanded','true');
		}
		if ($(accordionContent).hasClass('closed')) {
			$(accordionContent).attr('aria-hidden', 'true'); 
			$(this).attr('aria-expanded','false');
		}

		isAriaExp = $control.attr('aria-expanded');
		newAriaExp = (isAriaExp == "false") ? "true" : "false";
		$control.attr('aria-expanded', newAriaExp);
		isAriaHid = $(accordionContent).attr('aria-hidden');

		// If the accordion is closed then we need to open it
		// 1. First add the 'open' class so that it is visible
		// 2. Use jQuery animation to take the max-height from 0px to 500px.
		// * Note : at the end of the animation we will set the max-height to be the outerHeight so that the closing animation is smoother
		if (isAriaHid == "true") {
			$(accordionContent).addClass('open');
			$(accordionContent).removeClass('closed');
			$(accordionContent).attr('aria-hidden', "false");
			$(accordionContent).animate(
				{maxHeight:"1000px"}, 400, function() {
					// Once the animation is done set max-height to 100% so that if the div changes sizes it is not limited
					$(accordionContent).css('max-height','100%');
				});
		} else {
			// Convert max-height 100% to a pixel value that we can use 
			$(accordionContent).css('max-height', $(accordionContent).prop('scrollHeight'));
			var h = parseInt($(accordionContent).css('max-height'));
			// Calculate speed of closure
			// ms = accordionContent height in px * modifier (higher = faster, lower = slower)
			var ms = h * 1.5;
			// min 400ms and max 1000s for small/large accordions
			if (ms < 400) { ms = 400; }
			if (ms > 800) { ms = 800; }
			$(accordionContent).animate(
				{maxHeight:"0px"}, ms, function() {
					$(accordionContent).removeClass('open');
					$(accordionContent).addClass('closed');
					$(accordionContent).attr('aria-hidden', "true");
				});
		}
	});
}

function checkLink(link) {

	var link_pairs = [];
	link_pairs['https://learning.zoom.us/learn'] = 'https://zoom.us/saml2/idp/auth/zoomlearning';
	link_pairs['https://learning.zoom.us'] = 'https://zoom.us/saml2/idp/auth/zoomlearning';
	link_pairs['https://community.zoom.com/'] = 'https://zoom.us/community/sso?referer=https%3A%2F%2Fcommunity.zoom.com%2F';

	if (link_pairs[link] != null) { return link_pairs[link]; }
	else { return link; }

}