( function( $ ) {
	var body    			= $( 'body' ),
		html 				= $( 'html' ),
		onAirIntervalID 	= null,
		onAirInterval 		= 5000, // check every 5 seconds if we got data
		$marquee 			= null,
		smBreakpoint		= 768,
		supertopicAppended 	= false,
		eventCatInit		= false,
		_window				= $( window );

	var marqueeOptions = {
		duration: 15000, //speed in milliseconds of the marquee
		delayBeforeStart: 1000, //time in milliseconds before the marquee will start animating
		duplicated: true,
		pauseOnHover: true,
		startAtBeginning: true
	};

	var galleryAdId = 1;
	var ad_rendered_handled = false;
	var leaderboard_height = 0;
	var leaderboard_is_sticky = false;
	var prideOffset = 0;
	
	// On page ready
	$(document).ready(function(){
		loadAds();
		initMarquee();
		initCaptionClick();
		initSmartBanners();
		appendSupertopicSidebar();
		showReadMoreBtn();
		resizeVideoIframe(); 
		initEventCategoryFilter();
		homepageStickyAds();
		initLeaderboard();
		document.getElementById("leaderboard").addEventListener("creativeRendered", function (e) {
			if(e.detail.id === 'leaderboard') {
				leaderboard_height = e.detail?.slot?.renderedSize ? e.detail.slot.renderedSize[1] : 0;
				var spacing = calculateLeaderboardHeight();
				$("body").css("padding-top", spacing);
				//Add additional class in sidebar element to fix big box ad padding issue
				if (spacing < 120) {
					//Small leader board add
					$('#homepage-latest-sticky-ad-container').addClass('small-leaderboard-ad');
					$('#homepage-featured-sticky-ad-container').addClass('small-leaderboard-ad');
					$('#sidebar').addClass('small-leaderboard-ad');
					$('#latest-stories-sidebar').addClass('small-leaderboard-ad');
					// $('#contest-sidebar-ad').addClass('small-leaderboard-ad sticky');
					// $('.companionAd').addClass('small-leaderboard-ad sticky');					
				}
				if (spacing > 260) {
					//Taller leader board add
					$('#homepage-latest-sticky-ad-container').addClass('tall-leaderboard-ad');
					$('#homepage-featured-sticky-ad-container').addClass('tall-leaderboard-ad');					
					$('#sidebar').addClass('tall-leaderboard-ad');
					$('#latest-stories-sidebar').addClass('tall-leaderboard-ad');
					// $('#contest-sidebar-ad').addClass('tall-leaderboard-ad sticky');
					// $('.companionAd').addClass('tall-leaderboard-ad sticky');
				}
			}
		});
	});
	// On window resize
	$(window).resize(function() {
		resizeVideoIframe();
		appendSupertopicSidebar();
		loadAds();
		if (window.outerWidth < smBreakpoint) {
			initMarquee();
			$("#live-bar-sticky-wrapper").css("height", "40px");
		} else {
			destroyMarquee();
			$("#live-bar-sticky-wrapper").css("height", "75px");
		}
	});

	$(window).load(function(){
		scrollToMusicPolls();
	});

	/**
	 * Global function to load ads with .rdm-ad class
	 * @return
	 */
	window.rdmLoadAds = function() {
		loadAds();
	}

	function resizeVideoIframe() {
		$('.rdm-brightcove-videojs, .BrightcoveExperience').each(function() {
			var height = (parseInt($(this).width()) * 9) / 16 ;
			$(this).height(height);
		});
	}

	/**
	 * Initialize our marquee(s)
	 * @void
	 */
	function initMarquee() {
		onAirIntervalID = setInterval(checkData, onAirInterval);
		checkData();

		function checkData() {
			debug_log("checking on-air data...");
			if ( $('data-on-air') === '' )
				return false;

			// If there is text, we continue
			clearInterval(onAirIntervalID);
			begin();
		}

		function begin() {
			destroyMarquee();
			debug_log("starting marquee...", marqueeOptions);
			$('.on-now-marquee').css('width',  $('#live-bar-sticky-wrapper').outerWidth()  );
			$marquee = $('.on-now-marquee').marquee( marqueeOptions );
		}
	}

	/**
	 * Checks all the class of ad types, if there is no iFrame in the div (we are always in async mode now)
	 * Then hide the parent class (which contains the padding)
	 */
	function checkAds() {
		var ad_types = ['ad-leaderboard', 'ad-mobile-leaderboard', 'ad-bigbox'];
		for (i in ad_types) {
			$ads = $('.'+ad_types[i]);
			$ads.each(function( index ) {
				debug_log("check ad", $(this));
				if ($(this).find('iframe').length === 0) {
					$(this).parent().attr('style','display:none !important');
					debug_log("this has no ad in it, hiding...");
				} else {
					debug_log("has an ad, not doing anything");
				}
			});
		}
	}

	/**
	 * Loads all ads on page based on screen size
	 * Ads can be loaded on all screens, with a min/max window width, or a range.
	 * To use, create an element with the classes rdm-ad and unloaded,
	 * also must have a unique ID and an ad type.
	 * Examples:
	 * 1. Load on all sizes
	 * <div id="ad1" class="rdm-ad unloaded" data-all="true" data-type="_AD_BIGBOX"></div>
	 * 2. Load if screen if 1024px or larger
	 * <div id="ad2" class="rdm-ad unloaded" data-min="1024" data-type="_AD_BIGBOX"></div>
	 * 3. Load between a range
	 * <div id="ad3" class="rdm-ad unloaded" data-min="768" data-max="1023" data-type="_AD_BIGBOX"></div>
	 * @void
	 */
	function loadAds() {
		debug_log("checkings ads");
		$(".rdm-ad.unloaded").each(function(){
			if ( adIsEligible( $(this) ) ) {
				loadAd( $(this) );
			}
		});
	}

	/**
	 * Move and render native ad to the bottom of popular article list.
	 * @param  {[type]} elem Native ad container element;
	 * @param  {[type]} id   ID attribute of ad element
	 * @void
	 */
	function renderArticleSidebarNativeAd( elem, id ) {
		if ( window.outerWidth === 768 && navigator.userAgent.match(/iPad/i) !== null ) {
			return; // APS-122: don't insert native-ad for iPad portrait mode.
		}

		elem.parent().prev().find('.tptn_posts_widget > ul').append($('<li>').append(elem.clone()));
		elem.parent().remove();
		adUtility.insertAd( id, { type: adUtility._NATIVE_WEB, adPath: adUnitPath, targeting: adTargets({ 'nativearea': [ 'article' ] }) } );
	}

	/**
	 * Load individual ad
	 * @param  {[type]} id   ID attribute of ad element
	 * @param  {[type]} type Type of ad to be loaded
	 * @void
	 */
	function loadAd( elem ) {
		elem.removeClass("unloaded");
		id = elem.attr('id');
		dataType = elem.attr('data-type');

		switch (true) {
			case /ad-native-web-latest/.test(id):
				adUtility.insertAd( id, { type: adUtility._NATIVE_WEB, adPath: adUnitPath, targeting: adTargets({ 'nativearea': [ 'latest' ] })} );
				break;
			case /rogers-ad-widget-(\d+)-ad/.test(id) && '_NATIVE_WEB' === dataType:
				renderArticleSidebarNativeAd( elem, id );
				break;
			default:
				if( '_AD_BIGBOX' === $('#sidebar .inner #'+id).attr('data-type') && (window.innerWidth <= 768 || 834 === window.innerWidth)) {
					$('#sidebar .inner').prepend($('#sidebar .inner .sidebar-widget').first().html());
					$('#sidebar .inner .sidebar-widget').remove();
				} else {
					adUtility.insertAd(id, { type: adUtility[elem.data('type')], adPath: adUnitPath, targeting: adTargets() });
					break;
				}
		}
	}

	/**
	 * Set of rules to see if an ad is eligible to be loaded or not
	 * @param  {[type]} elem [description]
	 * @return {[type]}      [description]
	 */
	function adIsEligible( elem ) {
		if (
			( $(window).width() >= parseInt(elem.data('min')) && $(window).width() <= parseInt(elem.data('max')) ) ||
			( $(window).width() >= parseInt(elem.data('min')) && "undefined" == typeof elem.data('max') ) ||
			( $(window).width() <= parseInt(elem.data('max')) && "undefined" == typeof elem.data('min') ) ||
			( elem.data('all') )
		) {
			return true;
		}

		return false;
	}

	/**
	 * Remove all instances of the marquee
	 * @void
	 */
	function destroyMarquee() {
		debug_log("destroying marquee");
		if ($marquee !== null)
			$marquee.marquee('destroy');
	}

	/**
	 * Initialize the mobile caption show/hide click
	 * @void
	 */
	function initCaptionClick() {
		$("#show_hide_caption").click(function() {
			if ($(".caption-text").hasClass("mobile_hidden")) {
				$(this).text('Hide caption -');
				$(".caption-text").removeClass("mobile_hidden");
			} else {
				$(".caption-text").addClass("mobile_hidden");
				$(this).text('Show caption +');
			}
		});
	}

	/**
	 * Debug to console if 'debug_js=1'
	 * @void
	 */
	function debug_log(message, vars) {

		if ( (getQueryParam('debug_js') == '1') || (getQueryParam('debug_js') == 'true') ) {

			if (typeof vars !== 'undefined') {
				console.log(message, vars);
			} else {
				console.log(message);
			}
		}

	}

	function getQueryParam(name) {
		name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
		var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
			results = regex.exec(location.search);
		return results === null ? null : decodeURIComponent(results[1].replace(/\+/g, " "));
	}

	function appendSupertopicSidebar() {
		if ( ! $("body").hasClass("single-rogers_supertopic") ) {
			return false;
		}

		if ( window.outerWidth < 1024 && ! supertopicAppended ) {
			supertopicAppended = true;
			$("#sidebar").appendTo('#supertopic_bottom > .container');
			window.adUtility.refreshWithAsyncOn(["rogers-ad-widget-6-ad"]);
			window.adUtility.refreshWithAsyncOn(["rogers-ad-widget-7-ad"]);
		} else if ( window.outerWidth > 1023 && supertopicAppended ) {
			supertopicAppended = false;
			$("#sidebar").appendTo('#sidebar_container');
			window.adUtility.refreshWithAsyncOn(["rogers-ad-widget-6-ad"]);
			window.adUtility.refreshWithAsyncOn(["rogers-ad-widget-7-ad"]);
		}
	}

	function showReadMoreBtn() {
		if ( typeof MoreBtn !== "undefined" ) {
			if ( MoreBtn.show == 'show') {
				$(".external-more-btn").show();
			}
		}
	}

	function refreshSidebarAds() {
		window.adUtility.refreshWithAsyncOn(["rogers-ad-widget-3-ad"]);
		window.adUtility.refreshWithAsyncOn(["rogers-ad-widget-2-ad"]);
	}

	function alterArticleIframeWidth() {
		if ( ! $( 'body' ).hasClass( 'single-post' ) ) return;

		if ( window.outerWidth > 767 && window.outerWidth < 1025 ) {
			$( ".article-body iframe" ).css( "max-width", $( ".article-body" ).width() - $( "#sidebar" ).outerWidth() );
		}
	}

	function initSmartBanners() {
		$.smartbanner({
			title: null, // What the title of the app should be in the banner (defaults to <title>)
			author: 'Rogers Communications.', // What the author of the app should be in the banner (defaults to <meta name="author"> or hostname)
			price: 'FREE', // Price of the app
			appStoreLanguage: 'us', // Language code for App Store
			inAppStore: 'On the App Store', // Text of price for iOS
			inGooglePlay: 'In Google Play', // Text of price for Android
			icon: null, // The URL of the icon (defaults to <link>)
			iconGloss: null, // Force gloss effect for iOS even for precomposed (true or false)
			button: 'VIEW', // Text on the install button
			scale: 'auto', // Scale based on viewport size (set to 1 to disable)
			speedIn: 300, // Show animation speed of the banner
			speedOut: 400, // Close animation speed of the banner
			daysHidden: 15, // Duration to hide the banner after being closed (0 = always show banner)
			daysReminder: 90, // Duration to hide the banner after "VIEW" is clicked (0 = always show banner)
			force: null
		});
	}

	function updateVisibleEvents() {
		var selectedOptions = $('#event-categories option:selected').map(function() { return $(this).val() }).toArray();

		if (0 == selectedOptions.length) {
			$('.single-event-wrapper').show();
			return;
		}

		$('.single-event-wrapper').each(function() {
			var elem = $(this);
			var event_categories = elem.data('categories').toString().split(',');
			var show = false;

			for (var i = 0; i < selectedOptions.length; i++) {
				if (-1 != event_categories.indexOf(selectedOptions[i])) {
					show = true;
					break;
				}
			}

			show ? elem.show() : elem.hide();
		});
	}

	function initEventCategoryFilter() {
		$('#event-categories').multiselect({
			nonSelectedText: 'Select Category',
			onChange: updateVisibleEvents,
		});

		selectEventCategories();
	}

	function selectEventCategories() {
		if (null != getQueryParam('categories')) {
			$('#event-categories').multiselect('select', getQueryParam('categories').split(','));
			updateVisibleEvents();
		}
	}

	function scrollToMusicPolls() {
		if ($("#music-polls").length == 0) {
			return;
		}

		if ('#polls' == window.location.hash) {
			$("html, body").stop().animate({scrollTop:parseInt($("#music-polls").offset().top - 100)}, '2000', 'swing');
		}
	}

	function homepageStickyAds() {
		if ( $( 'body' ).hasClass( 'home' ) ) {
			var width = window.innerWidth

			if ( width >= 1440 ) {
				// Set height of featured section ad container
				var height = $( '.homepage-top' ).height();

				height -= $( '.homepage-first-sidebar' ).outerHeight();

				$( '#homepage-featured-sticky-ad-container' ).css( 'height', height );
			}

			if ( width >= 1024 ) {
				// Set height of featured section ad container
				var height = $( '.latest-stories-wrapper' ).height();

				$( '#homepage-latest-sticky-ad-container' ).css( 'height', height );

				var stickyElements = document.getElementsByClassName('sticky');

				for (var i = stickyElements.length - 1; i >= 0; i--) {
					Stickyfill.add(stickyElements[i]);
				}
				setTimeout(function(){
					var height = ( $( '.row.latest-stories-wrapper' ).height() - 100 ) + 'px';
					$( '#homepage-latest-sticky-ad-container' ).css( 'height', height );
				}, 4500);
			}
		}
	}
	function initLeaderboard() {
		var spacing = calculateLeaderboardHeight();
		$('#sticky_leaderboard').addClass('pinned');
		$("body").css("padding-top", spacing);
		$("body").addClass("has-leaderboard");

		var sticky = adUtility.stickyAd('leaderboard', {timeout: 5000, offset: 0, onUnstick: function() {
			var scrollTop = $(window).scrollTop();
			$(window).bind('scroll.maybeDoLeaderboardCallback', function() {
				// check if scrolling down
				var newScrollTop = $(window).scrollTop();

				if (newScrollTop > scrollTop) {
					$(window).unbind('.maybeDoLeaderboardCallback');
					leaderboardOffScrollCallback();
				}

				scrollTop = newScrollTop;
			});
		}});

		sticky.init();
		leaderboard_is_sticky = true;
		//initStickyElement($('#live-bar'), 0);
		//initStickyElement($('#live-bar'), spacing);
		//var prideOffset = calculateLiveBarHeight();
		//initStickyElement($('#pride-bar'), prideOffset, false);
	}
	function calculateLiveBarHeight() {
		// if(self.leaderboard_height == 250){
		// 	return 235;
		// } else if(self.leaderboard_height == 66){
		// 	return 56;
		// } else {
			return window.innerWidth > 767 ? 75 : 40;
		//}
	}
	function leaderboardOffScrollCallback() {
		$("body").css("padding-top", "0px");
		$("body").removeClass("has-leaderboard");

		leaderboard_is_sticky = false;

		initStickyElement($('#live-bar'), 0, true);

		if ("undefined" != typeof PrideBarSettings) {
			prideOffset = calculateLiveBarHeight();
			initStickyElement($('#pride-bar'), prideOffset, true, function() {
				$(window).resize(function() {
					maybeUpdatePridebarOffset();
				});
			});
		}

		Stickyfill.rebuild();
	};
	function initStickyElement(elem, offset, update, callback) {
		offset = "undefined" == typeof offset ? 0 : offset;
		update = "undefined" == typeof update ? false : true;

		if (update) {
			elem.unstick().sticky({ topSpacing: offset });
		} else {
			elem.sticky({ topSpacing: offset });
		}

		if ("function" == typeof callback) {
			callback();
		}
	}
	function calculateLeaderboardHeight() {
		if(leaderboard_height == 250){
			return 266;
		} else if(leaderboard_height == 66){
			return 82;
		} else {
			return window.innerWidth > 767 ? 106 : 66;
		}
	}

} )( jQuery );
$( document ).ready(function() {
	$(document).on('click', '.mp3123', function (event) {
		var mp3Audio = document.getElementById('rdm-mp3_html5');
		if(this.className == 'mp3123 glyphicon glyphicon-play'){
			this.className = "mp3123 glyphicon glyphicon-pause";
			mp3Audio.play();
		}else{
			this.className = "mp3123 glyphicon glyphicon-play";
			mp3Audio.pause();
		}
	});

	$(document).on('click', '#sideTextMP3', function (event) {
		$(".mp3123").click();
	});
});

//Move header primary nav link to More dropdown between 1024px to 1200px.
var executed_removelink = false;
var executed_addlink = false;
var executed_removelink_medium_nav = false;
var executed_addlink_medium_nav = false;
$cloneLink = $("#menu-header-full li:eq(2)").clone();

var removeLink = (function() {
    return function() {
        if (!executed_removelink) {
            executed_removelink = true;
			$($cloneLink).prependTo(".dropdown-menu");
			$("#menu-header-full li:eq(2)").remove();            
        }
    };
})();

var addLink = (function() {
    return function() {
        if (!executed_addlink) {
            executed_addlink = true;
			//Remove link from More dropdown
			$(".dropdown-menu > li:nth-child(1)").remove();
			$("#menu-header-full > li:nth-child(2)").after($cloneLink);
        }
    };
})();

var removeLinkMediumNav = (function() {
    return function() {
        if (!executed_removelink_medium_nav) {
            executed_removelink_medium_nav = true;
			//Remove link from More dropdown
			$(".dropdown-menu > li:nth-child(1)").remove();
        }
    };
})();

var addLinkMediumNav = (function() {
    return function() {
        if (!executed_addlink_medium_nav) {
            executed_addlink_medium_nav = true;
			//Remove link from More dropdown
			$($cloneLink).prependTo(".dropdown-menu");
        }
    };
})();

var viewport_width = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
if (viewport_width >= 1024 && viewport_width < 1440 && executed_removelink == false) {
	removeLink();
}
//Put back the removed link to primary nav
if(viewport_width >= 1440 && executed_removelink == true) {
	addLink();
}
//Remove extra link from medium nav
/* if(viewport_width < 1024 && executed_removelink_medium_nav == false) {
	removeLinkMediumNav();
	addLinkMediumNav();
}
//Add removed link from medium nav
if(viewport_width >= 1024 && executed_removelink_medium_nav == true) {
	addLinkMediumNav();
}	*/

//window resize event
$(window).on('resize', function() {
	viewport_width = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
	if (viewport_width >= 1024 && viewport_width < 1440 && executed_removelink == false) {
		removeLink();
	}
	//Put back the removed link to primary nav
	if(viewport_width >= 1440 && executed_removelink == true) {
		addLink();
	}
	//Remove extra link from medium nav
	if(viewport_width < 1024 && executed_removelink_medium_nav == false) {
		removeLinkMediumNav();
	}
	//Add removed link from medium nav
	if(viewport_width >= 1024 && executed_removelink_medium_nav == true) {
		addLinkMediumNav();
	}	
});

