// This file is used by 1) GNZ and 2) EG

// IE 11 fix for syntax compile
if (!String.prototype.startsWith) {
	String.prototype.startsWith = function (searchString, position) {
		position = position || 0;
		return this.indexOf(searchString, position) === position;
	};
}

$(function () {
	
	var $window = $(window)

	headerBgUpdate()
	headerDropdownLinks()
	mobileDropdownLinks()
	setupLayout()
	headerSearch()
	partnersCarousel()


	//setTimeout(function () { heroCarousel(); }, 500);	

	//galleryCarousel()
	//eventsCarousel()
	//tilesCarousel()
	videosCarousel()
	//faq()
	mobileMenu()

	//Phase 2
	//templateFilter()
	leaderboardTable()
	 


	function leaderboardTable() {
		var contentTrigger = $('.js-leaderboard')
		var contentClose = $('.js-row-content__close')
		var content = $('.table__row-content')
		var contentScroll = $('.row-content__scroll')

		var dataHoleButton = $('.js-hole-tab');

		contentScroll.scroll(function() {
			var elmnt = $(this)
			var x = elmnt.scrollLeft()
			if ( x > 10) {
				contentScroll.addClass('hide-mobile-gesture')
			}
		});
		
		contentTrigger.click(function() {
			if ($(this).next(content).hasClass('content-is-active')) {
				$(this).next(content).removeClass('content-is-active')
				$(this).next(content).slideUp(400);
			} else {
				content.slideUp(400);
				content.removeClass('content-is-active')
				$(this).next(content).addClass('content-is-active')
				$(this).next(content).slideDown(400);
				if ($( window ).width() < 1311) {
					content.addClass('remove-swipe');
				}
			}
		})

		contentClose.click(function() {
			content.slideUp(400);
			content.removeClass('content-is-active')
		})

		// For triggering hole tabs on mobile.
		dataHoleButton.click(function() {
			var dataHole = $(this).data("holes")
			var thisContainer = $(this).closest('.table__row-content')
			var tabs =  thisContainer.find('.js-hole-tab')
			var dataClass = 'data-holes-is-' + dataHole + ''

			if (!thisContainer.hasClass(dataClass)) {
				thisContainer.removeClass('data-holes-is-out')
				thisContainer.removeClass('data-holes-is-in')
				thisContainer.addClass(dataClass)
				tabs.removeClass('is-active')
				$(this).addClass('is-active')
			}
		})
	}

	

	// Scroll to top page 
	function scrollToTopDoc() {
		$('body').addClass('scroll-to-top-init')

		function showTop(){
			$('html,body').animate({ scrollTop: 0 }, 0);
			$('body').removeClass('scroll-to-top-init')
        	return false; 
		}
		setTimeout(showTop, 500);
	}
	$('.js-backToTop').click(function() {
		scrollToTopDoc()
	})
	// ----------------

	// Dropdown links for desktop navigation
	function headerDropdownLinks() {		
		var lgDropdownNav = $('.js-dropdown-navigation')
		//var lgDropdownTrigger = lgDropdownNav.find('.navigation__li')
		var dropdownOverlay = $('.dropdown-menu__overlay')
		//var lgDSection = $('.dropdown-menu__section')

		dropdownOverlay.click(function() {
			$('body').removeClass('dropdown-is-open')
			$('.navigation__li').removeClass('is-active')
			$(`.dropdown-menu__section`).removeClass('is-active')
		})

		lgDropdownNav.on('click', '.navigation__li', function () {
			$('body').addClass('dropdown-is-open')
			lgMagicNumber = $(this).data('menu-link');

			if ($(`.dropdown-menu__section[data-menu-section=${lgMagicNumber}]`).hasClass('is-active')) {
				$(`.dropdown-menu__section[data-menu-section=${lgMagicNumber}]`).removeClass('is-active')
				$('body').removeClass('dropdown-is-open')
				$('.navigation__li').removeClass('is-active')
			} else {
				$(`.dropdown-menu__section`).removeClass('is-active')
				$('.navigation__li').removeClass('is-active')
				$(`.dropdown-menu__section[data-menu-section=${lgMagicNumber}]`).addClass('is-active')
				$(this).addClass('is-active')
			}
		})
	}

	// Dropdown links for mobile navigation (accordion type functionality)
	function mobileDropdownLinks() {
		var dropdownNav = $('.js-mobile-dropdown')

		dropdownNav.on('click', '.navigation__li', function() {
			var dSection = dropdownNav.find('.menu-dropdown__section')

			magicNumber = $(this).data('menu-link')

			if ($(`.navigation__li[data-menu-link=${magicNumber}]`).hasClass('is-active')) {
				$(`.navigation__li[data-menu-link=${magicNumber}]`).removeClass('is-active')
				dSection.eq(magicNumber).hide(400)
			} else {
				dSection.hide(400)
				$(`.navigation__li`).removeClass('is-active')
				$(`.navigation__li[data-menu-link=${magicNumber}]`).addClass('is-active')
				dSection.eq(magicNumber).show(400)
				$(this).addClass('is-active')
			}
		})
	}

	// Scroll reveal functions
	// see : https://scrollrevealjs.org/api/reveal.html

	// Used for scrollReveal when triggered
    function animatingClass(el) {
        el.classList.add('is-animating')
	}
	// Generic scroll reveal functions
    ScrollReveal().reveal('.js-image-scale', {
		delay: 300,
		scale: 1.2,
		interval: 100,
        duration: 1400,
        distance: '0',
        origin: 'bottom',
		viewFactor: 0.25,
		opacity: 1,
		// container: '#container',
        beforeReveal: animatingClass
	})

	ScrollReveal().reveal('.js-custom-reveal', {
		delay: 300,
        duration: 0,
        distance: '0',
        origin: 'top',
		viewFactor: 0.3,
		opacity: 1,
		// container: '#container',
        beforeReveal: animatingClass
	})

	ScrollReveal().reveal('.js-fade-up', {
		delay: 250,
        duration: 600,
        distance: '16px',
        origin: 'bottom',
		viewFactor: 0.2,
		// container: '#container',
        beforeReveal: animatingClass
	})

	ScrollReveal().reveal('.js-fade-up-interval', {
		delay: 250,
		interval: 100,
        duration: 600,
        distance: '16px',
        origin: 'bottom',
		viewFactor: 0.2,
		// container: '#container',
        beforeReveal: animatingClass
	})

	ScrollReveal().reveal('.js-fade-up-interval2', {
		delay: 250,
		interval: 100,
        duration: 600,
        distance: '16px',
        origin: 'bottom',
		viewFactor: 0.2,
		// container: '#container',
        beforeReveal: animatingClass
	})
	ScrollReveal().reveal('.js-fade-up-interval3', {
		delay: 250,
		interval: 100,
        duration: 600,
        distance: '16px',
        origin: 'bottom',
		viewFactor: 0.2,
		// container: '#container',
        beforeReveal: animatingClass
	})

	ScrollReveal().reveal('.js-fade-up-rte', {
		delay: 250,
        duration: 600,
        distance: '16px',
        origin: 'bottom',
		// container: '#container',
        beforeReveal: animatingClass
	})
	/////////////////////////////////////////


	// Handle the header style updates once scrolled from top
	function headerBgUpdate() {
		if ($window.scrollTop() < 10)
            $('.site-header').removeClass('has-bg').addClass('is-top')
        else if ($window.scrollTop() >= 10) {
            $('.site-header').addClass('has-bg').removeClass('is-top')
        }
	}

	$window.scroll(_.throttle(function () {
		headerBgUpdate()
	}, 50))


	// General page layout when page loads 
	function setupLayout() {
		// footer size that updates as it is fixed at bottom of page
		function footerSize() {
			var footer = $('.site-footer')
			var header = $('.site-header')
			var siteContentContainer = $('.l_content-spacer')
			var footerHeight = footer.outerHeight()

			if ($(window).width() <= 767) {
				siteContentContainer.css('paddingBottom', "0")
				footer.css('position', "relative")
				footer.css('zIndex', "12")
			} else {
				siteContentContainer.css('paddingBottom', "" + footerHeight + "px")
				footer.css('position', "fixed")
				footer.css('zIndex', "0")
			}
		}

		// For making hero actually 100 vh on some mobiles.
		function resizeViewport() {
			let vh = window.innerHeight * 0.01;
			document.documentElement.style.setProperty('--vh', vh + 'px');
		  }

		$(window).resize(function () {
			footerSize()
			resizeViewport()
		})
		footerSize()
		resizeViewport()
	}

	// Show and hide header search 
	function headerSearch() {
		var openSearch = $('.js-open-search')
		var closeSearch = $('.js-close-search')
		var searchInput = $('#headerSearchInput')
		var doc = $('body')
		var lgDSection = $('.dropdown-menu__section')

		openSearch.click(function (event) {
			event.preventDefault();
			doc.addClass('search-is-open')
			doc.removeClass('dropdown-is-open')
			$('.navigation__li').removeClass('is-active')
			lgDSection.removeClass('is-active')
			searchInput.focus()
		})

		closeSearch.click(function () {
			event.preventDefault();
			doc.removeClass('search-is-open')
			searchInput.blur()
		})
	}

	// Mobile menu toggle
	function mobileMenu() {
		var doc = $('body')
		var sb = 0;
		$('.js-mobile-menu').click(function (){
			if (doc.hasClass('menu-is-open')) {
				doc.removeClass('menu-is-open')
				$(document).scrollTop(SB);
				
			} else {
				SB = $(document).scrollTop();
				doc.addClass('menu-is-open')
			}
		})
	}

	// Have commented out custom slide transition as it breaks when using autoplay.
	// Have also commented slidesPerGroup option with speed these can be uncommented if scroll all in view is required.
	function partnersCarousel() {
		$('.partners__carousel').each(function (index, elem) {
			var currentTranslate = 0;
			new Swiper(elem, {
				// virtualTranslate: 'true',
				slidesPerView: 2,
				spaceBetween: 16,
				// slidesPerGroup: 2,
				// speed: 600,
				lazy: {
					loadPrevNext: true,
				},
				autoplay: {
					delay: 4000,
					disableOnInteraction: false,
				},

				breakpoints: {
					640: {
						slidesPerView: 3,
						spaceBetween: 16,
						// slidesPerGroup: 3,
						// speed: 800,
						lazy: {
							loadPrevNext: true,
						},
					},
					768: {
						slidesPerView: 4,
						spaceBetween: 16,
						// slidesPerGroup: 4,
						// speed: 1000,
						lazy: {
							loadPrevNext: true,
						},
					},
					1100: {
						slidesPerView: 5,
						spaceBetween: 16,
						// slidesPerGroup: 5,
						// speed: 1200,
						lazy: {
							loadPrevNext: true,
						},
					},
					1520: {
						slidesPerView: 6,
						spaceBetween: 16,
						// slidesPerGroup: 6,
						// speed: 1400,
						lazy: {
							loadPrevNext: true,
						},
					}
				},
				navigation: {
					nextEl: jQuery(elem).siblings('.block-header').find('.sw-r'),
					prevEl: jQuery(elem).siblings('.block-header').find('.sw-l')
				},
				// on: {
					
				// 	setTranslate: function (translate) {

				// 		var swiper = this
				// 		var delay = 0
				// 		var delayAmount = 0.025

				// 		if (currentTranslate > translate) {
				// 			delay = 0
				// 			for (var i = 0; i < swiper.slides.length; i++) {
				// 				swiper.slides[i].style.transform = 'translate(' + translate + 'px' + ', 0px)'
				// 				swiper.slides[i].style.transitionDelay = '' + delay + 's'
				// 				delay = delay + delayAmount;
				// 			}

				// 		} else {
				// 			delay = swiper.slides.length * delayAmount 
				// 			for (var i = 0; i < swiper.slides.length; i++) {
				// 				swiper.slides[i].style.transform = 'translate(' + translate + 'px' + ', 0px)'
				// 				swiper.slides[i].style.transitionDelay = '' + delay + 's'
				// 				delay = delay - delayAmount;
				// 			}
				// 		}
				// 		currentTranslate = translate
				// 		return currentTranslate;
				// 	}
				// }
			})
		})
	}

	// Accordion Filter
	filterAccordion()
	function filterAccordion() {

		var $filterAccordion = $('.js-filter-accordion')
		var $filterAccordionTrigger = $filterAccordion.find('.filter-accordion__title')
		var $filterAccordionActiveClass = 'is-active'
		var $filterAccordionSpeed = 400

		$filterAccordionTrigger.click(function (e) {
			if ($(this).parent().hasClass($filterAccordionActiveClass)) {
				$(this).parent().removeClass($filterAccordionActiveClass)
				$(this).next('.filter-accordion__content').slideUp($filterAccordionSpeed)
			} else {
				// $(this).closest($filterAccordion).find('.filter-accordion__content').slideUp($filterAccordionSpeed)
				// $(this).closest($filterAccordion).find('.filter-accordion__item').removeClass($filterAccordionActiveClass)
				$(this).parent().addClass($filterAccordionActiveClass)
				$(this).next('.filter-accordion__content').slideDown($filterAccordionSpeed)
			}
		})
	}

	$(document).ready(function () {
		var stickyrightpanelhtml = $('.sticky-right-panel__inner').html();
		if ($(window).width() > 1440 && stickyrightpanelhtml != undefined) {
			let stickyHtml = stickyrightpanelhtml.trim();
			if (stickyHtml) {
				let stickySidebar = new StickySidebar('.sticky-right-panel', {
					topSpacing: 20,
					bottomSpacing: -27,
					containerSelector: '.main--two-column',
					innerWrapperSelector: '.sticky-right-panel__inner'
				})
            }
        }
	});	

	/////////////////////////////////////////	
})

function videoModal() {
    // Video modal

    var SB = 0;
    var videoBtn = $('[data-video]');
    function videoPlay($that) {
		if (!$('.video-modal').length) {
			$('body').prepend(
				'<div class="video-modal">' +
				'<div class="video-modal__overlay"></div>' +
				'<span class="video-modal__close large-screens button">' +
				'<svg class="icon-close">' +
				'<use xlink:href="#icon-close"></use>' +
				'</svg>' +
				'</span>' +
				'<div class="container">' +
				'<div class="video-modal__overlay no-bg"></div>' +
				'<div class="row u_justify-center">' +
				'<div class="col-10">' +
				'<div class="video-modal__inner">' +
				'<div class="video-modal__close-container">' +
				'<span class="video-modal__close small-screens button">' +
				'<svg class="icon-close">' +
				'<use xlink:href="#icon-close"></use>' +
				'</svg>' +
				'</span>' +
				'</div>' +
				'<div class="video-modal__video-container">' +

				'<div class="embed-responsive ratio-16by9">' +
				'<iframe class="video-modal__video embed-responsive-item" src="' + $that.attr('data-video') + '" allow="autoplay; fullscreen" allowfullscreen="true"></iframe>' +
				'</div>' +

				'</div>' +
				'</div>' +
				'</div>' +
				'</div>' +
				'</div>' +
				'</div>'
			)
		}
    }

    $(document).on('click', '.video-modal__overlay', function () {
        closeVideo()
    });
    $(document).on('click', '.video-modal__close', function () {
        closeVideo()
    });

    videoBtn.click(function (e) {
        e.preventDefault();
        SB = $(document).scrollTop();
        $('body').addClass('video-modal-is-active')
        var that = $(this);
        videoPlay(that)
    })

    function closeVideo() {
        $('body').removeClass('video-modal-is-active')
        $('.video-modal').remove();
        $(document).scrollTop(SB);
    }
}

function templateFilter() {
	var filterTriger = $('.js-filter-open')
	var parent = filterTriger.parent()
	var filterContent = parent.next('.filter-content-mobile')

	filterTriger.click(function (e) {
		e.preventDefault();

		if (parent.hasClass('is-active')) {
			parent.removeClass('is-active')
			filterContent.slideUp(400);
		} else {
			parent.addClass('is-active')
			filterContent.slideDown(400);
		}
	})
}

function videosCarousel() {
	$('.videos__carousel').each(function (index, elem) {
		var currentTranslate = 0;
		new Swiper(elem, {
			virtualTranslate: 'true',
			slidesPerView: 'auto',
			spaceBetween: 16,

			breakpoints: {
				640: {
					slidesPerView: 'auto',
					spaceBetween: 16
				}
			},
			pagination: {
				el: '.videos__carousel .swiper-pagination',
				type: 'progressbar',
			},
			navigation: {
				nextEl: jQuery(elem).siblings('.block-header').find('.sw-r'),
				prevEl: jQuery(elem).siblings('.block-header').find('.sw-l')
			},
			on: {
				init: function () {
					var swiper = this
					var slideCount = swiper.slides.length;

					if (slideCount < 10) {
						slideTotal = '0' + slideCount
					} else {
						slideTotal = slideCount
					}

					var swiperSlideLength = document.createTextNode("" + slideTotal + "");
					swiper.el.querySelector('.carousel__count--total').innerHTML = '';
					swiper.el.querySelector('.carousel__count--total').appendChild(swiperSlideLength);
				},
				setTranslate: function (translate) {

					var swiper = this
					var delay = 0
					var delayAmount = 0.025

					if (currentTranslate > translate) {
						delay = 0
						for (var i = 0; i < swiper.slides.length; i++) {
							swiper.slides[i].style.transform = 'translate(' + translate + 'px' + ', 0px)'
							swiper.slides[i].style.transitionDelay = '' + delay + 's'
							delay = delay + delayAmount;
						}

					} else {
						delay = swiper.slides.length * delayAmount
						for (var i = 0; i < swiper.slides.length; i++) {
							swiper.slides[i].style.transform = 'translate(' + translate + 'px' + ', 0px)'
							swiper.slides[i].style.transitionDelay = '' + delay + 's'
							delay = delay - delayAmount;
						}
					}
					currentTranslate = translate
					return currentTranslate;
				}
			}
		})
	})
}

function revealGeneric() {
	// Used for scrollReveal when triggered
	function animatingClass(el) {
		el.classList.add('is-animating')
	}

	// Generic scroll reveal functions
	ScrollReveal().reveal('.js-image-scale', {
		delay: 300,
		scale: 1.2,
		interval: 100,
		duration: 1400,
		distance: '0',
		origin: 'bottom',
		viewFactor: 0.25,
		opacity: 1,
		// container: '#container',
		beforeReveal: animatingClass
	})

	ScrollReveal().reveal('.js-fade-up', {
		delay: 250,
		duration: 600,
		distance: '16px',
		origin: 'bottom',
		viewFactor: 0.2,
		// container: '#container',
		beforeReveal: animatingClass
	})

	ScrollReveal().reveal('.js-custom-reveal', {
		delay: 300,
		duration: 0,
		distance: '0',
		origin: 'top',
		viewFactor: 0.3,
		opacity: 1,
		// container: '#container',
		beforeReveal: animatingClass
	})
}

function revealText() {
	// Used for scrollReveal when triggered
	function animatingClass(el) {
		el.classList.add('is-animating')
	}

	ScrollReveal().reveal('.js-fade-up-interval', {
		delay: 250,
		interval: 100,
		duration: 600,
		distance: '16px',
		origin: 'bottom',
		viewFactor: 0.2,
		// container: '#container',
		beforeReveal: animatingClass
	})

	ScrollReveal().reveal('.js-fade-up-interval2', {
		delay: 250,
		interval: 100,
		duration: 600,
		distance: '16px',
		origin: 'bottom',
		viewFactor: 0.2,
		// container: '#container',
		beforeReveal: animatingClass
	})

	ScrollReveal().reveal('.js-fade-up-interval3', {
		delay: 250,
		interval: 100,
		duration: 600,
		distance: '16px',
		origin: 'bottom',
		viewFactor: 0.2,
		// container: '#container',
		beforeReveal: animatingClass
	})

	ScrollReveal().reveal('.js-fade-up', {
		delay: 250,
		duration: 600,
		distance: '16px',
		origin: 'bottom',
		viewFactor: 0.2,
		// container: '#container',
		beforeReveal: animatingClass
	})

	ScrollReveal().reveal('.js-fade-up-rte', {
		delay: 250,
		duration: 600,
		distance: '16px',
		origin: 'bottom',
		// container: '#container',
		beforeReveal: animatingClass
	})
}

function revealArticles() {

	// Scroll reveal functions
	// see : https://scrollrevealjs.org/api/reveal.html

	// Used for scrollReveal when triggered
	function animatingClass(el) {
		el.classList.add('is-animating')
	}

	ScrollReveal().reveal('.js-image-scale-news', {
		delay: 300,
		scale: 1.2,
		interval: 100,
		duration: 1400,
		distance: '0',
		origin: 'bottom',
		viewFactor: 0.25,
		opacity: 1,
		// container: '#container',
		beforeReveal: animatingClass
	})

	ScrollReveal().reveal('.js-fade-up-interval-news', {
		delay: 250,
		interval: 100,
		duration: 600,
		distance: '16px',
		origin: 'bottom',
		viewFactor: 0.2,
		// container: '#container',
		beforeReveal: animatingClass
	})

	ScrollReveal().reveal('.js-fade-up-interval', {
		delay: 250,
		interval: 100,
		duration: 600,
		distance: '16px',
		origin: 'bottom',
		viewFactor: 0.2,
		// container: '#container',
		beforeReveal: animatingClass
	})
}

function faq(pcid) {
	var $faq = $('div[pc-id=' + pcid + '] .faq');
	var $faqActiveClass = 'is-active'
	var $faqSpeed = 400
	$('.faq__title', $faq).each(function (i) {
		$(this).on("click", function () {
			if ($(this).parent().hasClass($faqActiveClass)) {
				$(this).parent().removeClass($faqActiveClass)
				$(this).next('.faq__content').slideUp($faqSpeed)
			} else {
				$(this).closest($faq).find('.faq__content').slideUp($faqSpeed)
				$(this).closest($faq).find('.faq__item').removeClass($faqActiveClass)
				$(this).parent().addClass($faqActiveClass)
				$(this).next('.faq__content').slideDown($faqSpeed)
			}
        })
	});
}

function loadBgVideo() {
	// for background video fit and resizing
	$('.jquery-background-video').bgVideo({
		fadeIn: 500,
		pauseAfter: 0
	})
}


var swiperTransitionInterleaveOffset = 0.9; // Used for custom hero transition.
var vWidth = 1007;

//////////////////
function heroCarousel() {
	$('.hero__carousel').each(function (index, el) {
		var newClass = 'hero__carousel_' + index
		$(this).addClass(newClass)
		var slides = $(this).find('.swiper-slide')

		if (slides.length > 1) {
			new Swiper('.' + newClass, {
				loop: true,
				speed: 600,
				grabCursor: true,
				watchSlidesProgress: true,
				mousewheelControl: true,
				keyboardControl: true,
				loopedSlides: 1,
				autoplay: {
					delay: 5000,
					disableOnInteraction: false,
				},
				pagination: {
					el: '.hero__carousel .swiper-pagination',
					clickable: true,
					renderBullet: function (index, className) {
						return '<span class="' + className + '"> <svg class="pagination-circle" version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 130.2 130.2"><circle class="path circle" fill="none" stroke="#00E6A1" stroke-width="3" stroke-miterlimit="10" cx="65.1" cy="65.1" r="62.1" /></svg></span>';
					},
				},
				breakpoints: {
					1025: {
						direction: 'vertical',
					}
				},
				on: {
					progress: function () {
						if (window.navigator.userAgent.indexOf('Trident/') === -1) {
							var swiper = this
							var currentWindowWidth = $(document).width()
							if (currentWindowWidth > vWidth) {
								var innerOffset = swiper.height * swiperTransitionInterleaveOffset
							} else {
								var innerOffset = swiper.width * swiperTransitionInterleaveOffset
							}

							for (var i = 0; i < swiper.slides.length; i++) {
								var slideProgress = swiper.slides[i].progress
								var innerTranslate = slideProgress * innerOffset

								if (currentWindowWidth > vWidth) {
									swiper.slides[i].querySelector('.slide-inner').style.transform = 'translate3d(0,' + innerTranslate + 'px, 0)'
								} else {
									swiper.slides[i].querySelector('.slide-inner').style.transform = 'translate3d(' + innerTranslate + 'px,0, 0)'
								}
							}
						}
					},
					touchStart: function () {
						if (window.navigator.userAgent.indexOf('Trident/') === -1) {
							var swiper = this
							for (var i = 0; i < swiper.slides.length; i++) {
								swiper.slides[i].style.transition = ''
							}
						}
					},
					setTransition: function (speed) {

						if (window.navigator.userAgent.indexOf('Trident/') === -1) {
							var swiper = this
							for (var i = 0; i < swiper.slides.length; i++) {
								swiper.slides[i].style.transition = speed + 'ms'
								swiper.slides[i].querySelector(".slide-inner").style.transition = speed + "ms"
							}
						}
					}
				}
			})
		}
		else if (slides.length === 1) {
			slides.addClass('swiper-slide-active');
		}
	})
}

function GetParameterValues(param) {
	let reg = new RegExp("[?&]" + param + "=([^&#]*)", "i")
	let queryString = reg.exec(window.location.href)
	return queryString ? queryString[1] : null
}

function convertNewsArticleImages(htmlString) {
	var htmlObject = $('<div>' + htmlString + '<div>'); // jquery call
	var imgObject = htmlObject.find('img');

	for (i = 0; i < imgObject.length; i++) {
		var wrapper = $(`<div class="rte__image"><div class="image-reveal-container"></div><div class="rte__image__pattern">
<svg width="120" class="pattern" height="120" viewBox="0 0 120 120" fill="none" xmlns="http://www.w3.org/2000/svg">
    <path d="M4.29294 0H5.70715L0 5.70715L0 4.29294L4.29294 0Z" class="fill"/>
    <path d="M0 14.2929V15.7072L15.7072 0H14.2929L0 14.2929Z" class="fill"/>
    <path d="M24.2929 0L0 24.2929L0 25.7072L25.7072 0H24.2929Z" class="fill"/>
    <path d="M34.2929 0L0 34.2929V35.7072L35.7072 0H34.2929Z" class="fill"/>
    <path d="M44.2929 0L0 44.2929L0 45.7072L45.7072 0H44.2929Z" class="fill"/>
    <path d="M54.2929 0L0 54.2929V55.7072L55.7072 0H54.2929Z" class="fill"/>
    <path d="M64.2929 0L0 64.2929L0 65.7072L65.7072 0H64.2929Z" class="fill"/>
    <path d="M74.2929 0L0 74.2929V75.7072L75.7072 0H74.2929Z" class="fill"/>
    <path d="M84.2929 0L0 84.2929L0 85.7072L85.7072 0H84.2929Z" class="fill"/>
    <path d="M94.2929 0L0 94.2929V95.7072L95.7072 0H94.2929Z" class="fill"/>
    <path d="M104.293 0L0 104.293L0 105.707L105.707 0H104.293Z" class="fill"/>
    <path d="M114.293 0L0 114.293V115.707L115.707 0H114.293Z" class="fill"/>
    <path d="M120 4.29294L4.29294 120H5.70715L120 5.70715V4.29294Z" class="fill"/>
    <path d="M120 14.2929L14.2929 120H15.7072L120 15.7072V14.2929Z" class="fill"/>
    <path d="M120 24.2929L24.2929 120H25.7072L120 25.7072V24.2929Z" class="fill"/>
    <path d="M120 34.2929L34.2929 120H35.7072L120 35.7072V34.2929Z" class="fill"/>
    <path d="M120 44.2929L44.2929 120H45.7071L120 45.7072V44.2929Z" class="fill"/>
    <path d="M120 54.2929L54.2929 120H55.7071L120 55.7072V54.2929Z" class="fill"/>
    <path d="M120 64.2929L64.2929 120H65.7071L120 65.7072V64.2929Z" class="fill"/>
    <path d="M120 74.2929L74.2929 120H75.7071L120 75.7072V74.2929Z" class="fill"/>
    <path d="M120 84.2929L84.2929 120H85.7071L120 85.7072V84.2929Z" class="fill"/>
    <path d="M120 94.2929L94.2929 120H95.7072L120 95.7072V94.2929Z" class="fill"/>
    <path d="M120 104.293L104.293 120H105.707L120 105.707V104.293Z" class="fill"/>
    <path d="M120 114.293L114.293 120H115.707L120 115.707V114.293Z" class="fill"/>
</svg>
                                </div></div>`);
		wrapper.find('.image-reveal-container').prepend(imgObject[i].outerHTML);
		//$(htmlObject).find('img').replaceWith($(wrapper[0]));
		$(imgObject[i]).replaceWith($(wrapper[0]));
	}	

	return $(htmlObject)[0].outerHTML;
}

function convertNewsArticleImagesSg(htmlString) {
	var htmlObject = $('<div>' + htmlString + '<div>'); // jquery call
	var imgObject = htmlObject.find('img');

	for (i = 0; i < imgObject.length; i++) {
		var wrapper = $(`<div class="rte__image"><div class="image-reveal-container"></div><div class="rte__image__pattern">
<svg width="64" height="192" viewBox="0 0 64 192" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M10.0369 18.6211C7.31581 23.3885 4.28353 28.0852 4.91213 33.823C5.35085 37.9106 8.67275 41.8804 10.7924 45.2493C18.7094 57.7938 17.8338 57.3267 32.89 57.0619C47.8486 56.8344 46.9932 57.3243 53.874 44.6051C55.2623 42.0343 56.7637 39.4892 57.8883 36.7691C58.9589 34.1557 59.356 30.3178 58.3473 27.5587C57.1278 24.1565 54.7328 21.082 52.797 18.0823C44.8747 5.9533 45.7221 6.41391 31.0002 6.51669C16.1677 6.71335 17.0166 6.25176 10.015 18.5864L10.0369 18.6211Z" fill="#8AC2E6" fill-opacity="0.35"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M10.0369 82.6211C7.31581 87.3885 4.28353 92.0852 4.91213 97.823C5.35085 101.911 8.67275 105.88 10.7924 109.249C18.7094 121.794 17.8338 121.327 32.89 121.062C47.8486 120.834 46.9932 121.324 53.874 108.605C55.2623 106.034 56.7637 103.489 57.8883 100.769C58.9589 98.1557 59.356 94.3178 58.3473 91.5587C57.1278 88.1565 54.7328 85.082 52.797 82.0823C44.8747 69.9533 45.7221 70.4139 31.0002 70.5167C16.1677 70.7133 17.0166 70.2518 10.015 82.5864L10.0369 82.6211Z" fill="#8AC2E6" fill-opacity="0.35"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M10.0369 146.621C7.31581 151.389 4.28353 156.085 4.91213 161.823C5.35085 165.911 8.67275 169.88 10.7924 173.249C18.7094 185.794 17.8338 185.327 32.89 185.062C47.8486 184.834 46.9932 185.324 53.874 172.605C55.2623 170.034 56.7637 167.489 57.8883 164.769C58.9589 162.156 59.356 158.318 58.3473 155.559C57.1278 152.156 54.7328 149.082 52.797 146.082C44.8747 133.953 45.7221 134.414 31.0002 134.517C16.1677 134.713 17.0166 134.252 10.015 146.586L10.0369 146.621Z" fill="#8AC2E6" fill-opacity="0.35"/>
</svg>
                                </div></div>`);
		wrapper.find('.image-reveal-container').prepend(imgObject[i].outerHTML);
		//$(htmlObject).find('img').replaceWith($(wrapper[0]));
		$(imgObject[i]).replaceWith($(wrapper[0]));
	}

	return $(htmlObject)[0].outerHTML;
}

function convertNewsArticleImagesEg(htmlString) {
	var htmlObject = $('<div>' + htmlString + '<div>');
	var imgObject = htmlObject.find('img');
	for (i = 0; i < imgObject.length; i++) {
		var wrapper = $(`<div class="rte__image"><div class="image-reveal-container"></div></div>`);
		wrapper.find('.image-reveal-container').prepend(imgObject[i].outerHTML);
		$(imgObject[i]).replaceWith($(wrapper[0]));
	}
	return $(htmlObject)[0].outerHTML;
}

function convertNewsiFramesEg(htmlString) {
	var htmlObject = $('<div>' + htmlString + '<div>');
	var imgObject = htmlObject.find('iframe');
	for (i = 0; i < imgObject.length; i++) {
		var wrapper = $(`<div class="rte__iframe"><div class="video__container"></div></div>`);
		wrapper.find('.video__container').prepend(imgObject[i].outerHTML);
		$(imgObject[i]).replaceWith($(wrapper[0]));
	}
	return $(htmlObject)[0].outerHTML;
}

function convertLinkButtons(htmlString) {
	var htmlObject = $('<div>' + htmlString + '<div>');
	var linkButtonObject = htmlObject.find('.btn-link');
	for (i = 0; i < linkButtonObject.length; i++) {
		var linkText = linkButtonObject[i].innerHTML;
		var linkHref = linkButtonObject[i].href;
		var linkTarget = linkButtonObject[i].target;
		var wrapper = $(`<div class="button-container"><a class="button button--primary" href="` + linkHref + `" target="` + linkTarget + `"></a></div>`);
		wrapper.find('.button--primary').prepend('<span class="button__text">' + linkText + '</span><span class="button__icon"><svg class="icon-arrow"><use xlink:href="#icon-arrow"></use></svg></span>');
		$(linkButtonObject[i]).replaceWith($(wrapper[0]));
	}
	return $(htmlObject)[0].outerHTML;
}

// Events
var eventsCarouselObj = {};
function eventsCarousel() {
	$('.events__carousel').each(function (index, elem) {
		var currentTranslate = 0;
		var controlId = $(this).parents('.pc-root-container').attr('pc-id');
		if (!!eventsCarouselObj['events__carousel-' + controlId]) {
			var swiper = eventsCarouselObj['events__carousel-' + controlId];
			swiper.update();
		} else {
			eventsCarouselObj['events__carousel-' + controlId] = new Swiper(elem, {
				virtualTranslate: 'true',
				slidesPerView: 'auto',
				watchSlidesProgress: true,
				spaceBetween: 16,
				pagination: {
					el: '.swiper-pagination',
					type: 'progressbar',
				},
				navigation: {
					nextEl: '.swiper-button-next',
					prevEl: '.swiper-button-prev'
				},
				on: {
					init: function () {
						var swiper = this
						var slideCount = swiper.slides.length;

						if (slideCount < 10) {
							slideTotal = '0' + slideCount
						} else {
							slideTotal = slideCount
						}

						var swiperSlideLength = document.createTextNode("" + slideTotal + "");
						swiper.el.querySelector('.carousel__count--total').innerHTML = '';
						if (swiper.el.querySelector('.carousel__count--total')) {
							swiper.el.querySelector('.carousel__count--total').appendChild(swiperSlideLength);
						}
					},
					update: function () {
						var swiper = this
						var slideCount = swiper.slides.length;

						if (slideCount < 10) {
							slideTotal = '0' + slideCount
						} else {
							slideTotal = slideCount
						}

						var swiperSlideLength = document.createTextNode("" + slideTotal + "");
						swiper.el.querySelector('.carousel__count--total').innerHTML = '';
						if (swiper.el.querySelector('.carousel__count--total')) {
							swiper.el.querySelector('.carousel__count--total').appendChild(swiperSlideLength);
						}
                    },
					setTranslate: function (translate) {

						var swiper = this
						var delay = 0
						var delayAmount = 0.025

						if (currentTranslate > translate) {
							delay = 0
							for (var i = 0; i < swiper.slides.length; i++) {
								swiper.slides[i].style.transform = 'translate(' + translate + 'px' + ', 0px)'
								swiper.slides[i].style.transitionDelay = '' + delay + 's'
								delay = delay + delayAmount;
							}

						} else {
							delay = swiper.slides.length * delayAmount
							for (var i = 0; i < swiper.slides.length; i++) {
								swiper.slides[i].style.transform = 'translate(' + translate + 'px' + ', 0px)'
								swiper.slides[i].style.transitionDelay = '' + delay + 's'
								delay = delay - delayAmount;
							}
						}
						currentTranslate = translate
						return currentTranslate;
					}
				}
			});
        }		
	})
}

// Tiles
function tilesCarousel() {
	$('.tiles__carousel').each(function (index, elem) {
		var currentTranslate = 0;
		new Swiper(elem, {
			virtualTranslate: 'true',
			slidesPerView: 'auto',
			watchSlidesProgress: true,
			spaceBetween: 16,
			breakpoints: {
				640: {
					slidesPerView: 'auto',
					spaceBetween: 16
				},
				768: {
					slidesPerView: 'auto',
					spaceBetween: 16
				},
				1100: {
					slidesPerView: 'auto',
					spaceBetween: 32
				}
			},
			pagination: {
				el: '.swiper-pagination',
				type: 'progressbar',
			},
			navigation: {
				nextEl: jQuery(elem).siblings('.block-header').find('.sw-r'),
				prevEl: jQuery(elem).siblings('.block-header').find('.sw-l')
			},
			on: {
				init: function () {
					var swiper = this
					var slideCount = swiper.slides.length; 

					if (slideCount < 10) {
						slideTotal = '0' + slideCount
					} else {
						slideTotal = slideCount
					}

					var swiperSlideLength = document.createTextNode("" + slideTotal + "");	
					const count = swiper.el.querySelector('.carousel__count--total');
					if (count) {
						count.innerHTML = '';
						count.appendChild(swiperSlideLength);
					}
				},
				setTranslate: function (translate) {

					var swiper = this
					var delay = 0
					var delayAmount = 0.025

					if (currentTranslate > translate) {
						delay = 0
						for (var i = 0; i < swiper.slides.length; i++) {
							swiper.slides[i].style.transform = 'translate(' + translate + 'px' + ', 0px)'
							swiper.slides[i].style.transitionDelay = '' + delay + 's'
							delay = delay + delayAmount;
						}

					} else {
						delay = swiper.slides.length * delayAmount
						for (var i = 0; i < swiper.slides.length; i++) {
							swiper.slides[i].style.transform = 'translate(' + translate + 'px' + ', 0px)'
							swiper.slides[i].style.transitionDelay = '' + delay + 's'
							delay = delay - delayAmount;
						}
					}
					currentTranslate = translate
					return currentTranslate;
				}
			}
		})
	})
}


function tableScrollReveal() {

	// Used for scrollReveal when triggered
	function animatingClass(el) {
		el.classList.add('is-animating')
	}

	ScrollReveal().reveal('.js-fade-up-interval', {
		delay: 250,
		interval: 100,
		duration: 600,
		distance: '16px',
		origin: 'bottom',
		viewFactor: 0.2,
		// container: '#container',
		beforeReveal: animatingClass
	})
}

function galleryCarousel(spaceBetweenValue = 140, spaceBetweenValueSmallerView = 64, spaceBetweenValueMobile = 16) {
	$('.gallery__carousel').each(function (index, elem) {
		new Swiper(elem, {
			speed: 500,
			slidesPerView: 1,
			spaceBetween: spaceBetweenValueMobile,
			centeredSlides: true,
			watchSlidesProgress: true,
			loopedSlides: 3,
			loop: true,
			breakpoints: {
				768: {
					slidesPerView: 1,
					spaceBetween: spaceBetweenValueSmallerView,
					centeredSlides: true
				},
				980: {
					slidesPerView: 1,
					spaceBetween: spaceBetweenValue,
					centeredSlides: true
				},
			},
			pagination: {
				el: '.gallery__carousel .swiper-pagination',
				type: 'progressbar',
			},
			navigation: {
				nextEl: '.swiper-button-next',
				prevEl: '.swiper-button-prev'
			},
			on: {
				init: function () {
					var swiper = this
					var slideCount = swiper.slides.length - 6;

					if (slideCount < 10) {
						slideTotal = '0' + slideCount
					} else {
						slideTotal = slideCount
					}

					var swiperSlideLength = document.createTextNode("" + slideTotal + "");
					if (swiper.el.querySelector('.carousel__count--total')) {
						swiper.el.querySelector('.carousel__count--total').innerHTML = '';
						swiper.el.querySelector('.carousel__count--total').appendChild(swiperSlideLength);
                    }
				}
			}
		})
	})
}

function newsFeatured() {
	$('.news-featured-swiper').each(function (index, elem) {
		var currentTranslate = 0;
		new Swiper(elem, {
			virtualTranslate: 'true',
			slidesPerView: 'auto',
			watchSlidesProgress: true,
			breakpoints: {
				640: {
					slidesPerView: 'auto',
				},
				768: {
					slidesPerView: 'auto',
				}
			},
			pagination: {
				el: '.news-featured-swiper .swiper-pagination',
				type: 'progressbar',
			},
			navigation: {
				nextEl: jQuery(elem).siblings('.block-header').find('.sw-r'),
				prevEl: jQuery(elem).siblings('.block-header').find('.sw-l')
			},
			on: {
				setTranslate: function (translate) {

					var swiper = this
					var delay = 0
					var delayAmount = 0.025

					if (currentTranslate > translate) {
						delay = 0
						for (var i = 0; i < swiper.slides.length; i++) {
							swiper.slides[i].style.transform = 'translate(' + translate + 'px' + ', 0px)'
							swiper.slides[i].style.transitionDelay = '' + delay + 's'
							delay = delay + delayAmount;
						}

					} else {
						delay = swiper.slides.length * delayAmount
						for (var i = 0; i < swiper.slides.length; i++) {
							swiper.slides[i].style.transform = 'translate(' + translate + 'px' + ', 0px)'
							swiper.slides[i].style.transitionDelay = '' + delay + 's'
							delay = delay - delayAmount;
						}
					}
					currentTranslate = translate
					return currentTranslate;
				}
			}
		})
	})
}

function initResourceHubBlockSlider(className) {
	$('.' + className + ' .resources__swiper').each(function (index, elem) {
		new Swiper(elem, {
			slidesPerView: 1.1,
			slidesPerGroup: 1,
			spaceBetween: 8,
			breakpoints: {
				1024: {
					slidesPerView: 3,
					slidesPerGroup: 3,
					spaceBetween: 30,
					navigation: {
						nextEl: jQuery(elem).parent('.resources__block--tiles').find('.swiper-button-next'),
						prevEl: jQuery(elem).parent('.resources__block--tiles').find('.swiper-button-prev')
					}
				}
			},
			pagination: {
				el: '.resources__swiper swiper-pagination',
				clickable: true
			},
			navigation: {
				nextEl: '.swiper-button-next',
				prevEl: '.swiper-button-prev'
			},
			on: {
				init: function () {
					jQuery(elem).parent('.resources__block--tiles').find('.swiper-button-prev').removeClass('hide');
					jQuery(elem).parent('.resources__block--tiles').find('.swiper-button-next').removeClass('hide');
                }
            }
		})
	})
}

//function viewAllRealatedNews(tags) {
//	window.open(`/news?tags=${tags}`);
//}


function preventBackgroundScroll() {
	// When DIV overlay is shown, prevent background scroll.            
	document.body.style.position = 'fixed';
	document.body.style.top = `-${window.scrollY}px`;
}

function normaliseBackgroundScroll(element) {
	// When DIV overlay is hidden (or closed), normalise page scroll.            
	document.body.style.position = '';
	document.body.style.top = '';

	var rec = document.getElementById(element).getBoundingClientRect();
	var pos = { top: rec.top + window.scrollY - 100, left: rec.left + window.scrollX };
	window.scrollTo(pos.left, pos.top);
}




/**
* ==============================
* BoF: Reusable modal dialogs
* ==============================
* @param message Message to be displayed on the modal.
* @param yesButtonText [Optional] text to be displayed on the yes button. Pass undefined to have it use the default button text.
* @param cancelButtonText [Optional] text to be displayed on the cancel button. Pass undefined to have it use the default button text.
*/
async function userConfirmationModal(htmlMessage, yesButtonText, cancelButtonText) {
	let modal = new Promise(function (resolve, reject) {
		if (!$('.user-custom__confirmation-modal').length) {
			$('body').prepend(
				'<div id="userCustomConfirmModal" class="modal admin-view user-custom__confirmation-modal" tabindex="-1" role="dialog" aria-labelledby="customUserConfirmModalLabel" aria-hidden="true" data-backdrop="static" keyboard="false">' +
				'	<div class="modal-dialog modal-dialog-centered" role="document">' +
				'		<div class="modal-content">' +
				'			<div class="modal-body">' +
				'				<div id="confirm-dialog-text" class="text-align-center">' +
				'					<span>New confirmation message must be appended here.</span>' +
				'				</div>' +
				'			</div>' +
				'			<div class="modal-footer">' +
				'				<button id="btnConfirmCancel" type="button" class="btn btn-secondary btn-lg" data-dismiss="modal" aria-label="Close">No</button>' +
				'				<button id="btnConfirmYes" type="button" class="btn btn-primary btn-lg">Yes</button>' +
				'			</div>' +
				'		</div>' +
				'	</div>' +
				'</div>'
			)
		}

		let modalId = '#userCustomConfirmModal';
		let confirmButton = `${modalId} #btnConfirmYes`;
		let cancelButton = `${modalId} #btnConfirmCancel`;

		$(modalId).on('show.bs.modal', function (e) {
			$(modalId).find('.modal-body > div#confirm-dialog-text').empty().append(htmlMessage);

			if (yesButtonText) {
				$(confirmButton).html(yesButtonText);
			}
			if (cancelButtonText) {
				$(cancelButton).html(cancelButtonText);
			}
		});

		$(modalId).modal('show');

		$(confirmButton).off('click').click(function () {
			$(modalId).modal('hide');
			$('.user-custom__confirmation-modal').remove();
			resolve(true);
		});

		$(cancelButton).off('click').click(function () {
			$(modalId).modal('hide');
			$('.user-custom__confirmation-modal').remove();
			reject(false);
		});
	});

	await modal;
}


/**		
* @param message Message to be displayed on the modal.
* @param buttonText [Optional] text to be displayed on the close button. Pass undefined to have it use the default button text.
*/
function userMessageModal(htmlMessage, buttonText) {
	if (!$('.user-custom__message-modal').length) {
		$('body').prepend(
			'<div id="userCustomMessageModal" class="modal admin-view user-custom__message-modal" tabindex="-1" role="dialog" aria-labelledby="userCustomMessageModalLabel" aria-hidden="true" data-backdrop="static" keyboard="false">' +
			'	<div class="modal-dialog modal-dialog-centered" role="document">' +
			'		<div class="modal-content">' +
			'			<div class="modal-body">' +
			'				<div id="message-dialog-text" class="text-align-center">' +
			'					<span>New message must be appended here.</span>' +
			'				</div>' +
			'			</div>' +
			'			<div class="modal-footer">' +
			'				<button id="btnMessageClose" type="button" class="btn btn-secondary btn-lg" data-dismiss="modal" aria-label="Close">Close</button>' +
			'			</div>' +
			'		</div>' +
			'	</div>' +
			'</div>'
		)
	}


	let modalId = '#userCustomMessageModal';
	let closeButton = `${modalId} #btnMessageClose`;

	$(modalId).on('show.bs.modal', function (e) {
		$(modalId).find('.modal-body > div#message-dialog-text').empty().append(htmlMessage);

		if (buttonText) {
			$(closeButton).html(buttonText);
		}
	});

	$(modalId).modal('show');

	$(closeButton).off('click').click(function () {
		$(modalId).modal('hide');
	});
}
/**
 * EoF: Reusable modal dialogs
 * */



function portraitVideoModal() {
	let scrollValue = 0;
	
	function playPortraitVideo() {
		if (!$('.video-modal').length) {
			$('body').prepend(
				'<div class="video-modal">' +
				'   <div class="video-modal__overlay">' +
				'       <span class="video-modal__close large-screens button">' +
				'           <svg class="icon-close">' +
				'               <use xlink:href="#icon-close"></use>' +
				'           </svg>' +
				'       </span>' +
				'       <div class="container">' +
				'           <div class="video-modal__overlay no-bg">' +
				'               <div class="row u_justify-center">' +
				'                   <div class="col-12 p-0">' +
				'                       <div class="video-modal__inner">' +
				'                           <div class="video-modal__close-container">' +
				'                               <span class="video-modal__close small-screens button">' +
				'                                   <svg class="icon-close">' +
				'                                       <use xlink:href="#icon-close"></use>' +
				'                                   </svg>' +
				'                               </span>' +
				'                           </div>' +
				'                           <div class="video-modal__portrait">' +
				'                               <iframe width="425" height="755" src="' + $(this).attr('data-video') + '" frameborder="0" allow="autoplay; fullscreen" allowfullscreen"true"></iframe>' +
				'                           </div>' +
				'                       </div>' +
				'                   </div>' +
				'               </div>' +
				'           </div>' +
				'       </div>' +
				'   </div>' +
				'</div>'
			)
		}

		scrollValue = $(document).scrollTop();
		$('body').addClass('video-modal-is-active');
	}

	function closePortraitVideo() {
		$('body').removeClass('video-modal-is-active')
		$('.video-modal').remove();
		$(document).scrollTop(scrollValue);
	}

	$(document).off('click', '.video-modal__overlay', closePortraitVideo).on('click', '.video-modal__overlay', closePortraitVideo);
	$(document).off('click', '.video-modal__close', closePortraitVideo).on('click', '.video-modal__close', closePortraitVideo);
	$(document).off('click', '.vbg__btn-play', playPortraitVideo).on('click', '.vbg__btn-play', playPortraitVideo);
	
}