$(document).ready(function() {initNowLeaving();});

var defaultImage = new Image();
var gemImage = new Image();
function preloadLeavingAssets() {
	defaultImage.src = '/kidscbc2/content/images/now-leaving.png';
	gemImage.src = '/kidscbc2/content/images/leaving-gem-popup.png';
}

function isOutboundLink(href) {
	function isLocal() {
		var home = window.location.hostname + "/kidscbc2";
		return href.includes(home);
	}
	
	function isNewKids() {
		return href.includes("/kids/");
	}
	
	function isRelativePath() {
		return href[0] === '/';
	}

	function isAnchorTag() {
		return href[0] === '#';
	}

	return (!isLocal() && !isNewKids() && !isRelativePath() && !isAnchorTag());
}

function createDefaultLightbox(href) {
	$.fancybox.open(' \
		<div aria-modal="true" aria-role="dialog" aria-label="You are now leaving Kids\' CBC" class="leaving_box"> \
			<img class="" id="now_leaving_dialogue" width="100%" alt="You are now leaving Kids\' CBC" src="'+ defaultImage.src +'" /> \
			<div class="buttons"> \
				<a href="#" aria-role="button" tabindex="2" aria-label="No, I don\'t want to leave the site." class="cancel">CANCEL</a> \
				<a href="'+ href +'" aria-role="button" aria-label="Yes, I want to leave the site." tabindex="1" target="_blank" class="okay">OKAY</a> \
			</div> \
		</div>'
	);
}

function createWatchLightbox(href) {
	$.fancybox.open(' \
		<div aria-modal="true" aria-role="dialog" aria-label="You are now leaving Kids\' CBC" class="leaving_box"> \
			<img class="" id="now_leaving_dialogue" width="100%" alt="You are now leaving Kids\' CBC" src="'+ gemImage.src +'" /> \
			<div class="buttons"> \
				<a href="#" aria-role="button" tabindex="2" aria-label="No, I don\'t want to leave the site and go to CBC Gem." class="cancel">CANCEL</a> \
				<a href="'+ href +'" aria-role="button" aria-label="Yes, I want to leave the site and go to CBC Gem." tabindex="1" target="_blank" class="okay">OKAY</a> \
			</div> \
		</div>'
	);
}

function initNowLeaving() {
	preloadLeavingAssets();

	$('a').each(function() {
		var href = $(this).attr('href');

		if (href !== undefined && isOutboundLink(href)) {
			if (!$(this).hasClass('carousel-control') && !$(this).hasClass('search-filter')) {
				$(this).on('click', function(e) {
					e.preventDefault();

					var cbcGemURLs = ['watch.cbc.ca', 'gem.cbc.ca'];
					var doesContainGemURL = cbcGemURLs.filter(e => href.includes(e)).length > 0;
					if (doesContainGemURL) {createWatchLightbox(href);} else {createDefaultLightbox(href);}

					$('.leaving_box .buttons .cancel').click(function(e) {
						e.preventDefault();
						forceLightboxClose();
					});
				});
			}
		}
	});
}

function forceLightboxClose() {$.fancybox.close();}
