// ===================================================================================
// LISTENERS

var lockOnResize = 0

$(document).ready( function() {

    let wysiwygTable = $('article.article_wysiwyg table');
    for (let i = 0; i < wysiwygTable.length; i++) {
        $('article.article_wysiwyg table')[i].outerHTML = '<div style="overflow-x:auto">'+$('article.article_wysiwyg table')[i].outerHTML+'</div>';
    }

    $('div.div_imagetextblock_textcontainer h2, div.div_imagetextblock_textcontainer p, a.a_standardlink').each( function() {
		$(this).html('<span>' + $(this).html() + '</span>');
    });

	$('iframe').attr('frameborder', '0');

	if ($('div.stickycta').length > 0) {
		$('body').css({'padding-bottom' : $('div.stickycta').outerHeight(true)-25 + 'px'});
	}

	if ($.cookie('cc_CLOSED_FOOTER') == 'true') {
        $('a#show_hide_footer').next().css('height', '0px');
        $('body').css({'padding-bottom' : '0px'});
    } else {
		$('a#show_hide_footer').text('-');
		$('body').css({'padding-bottom' : $('div.stickycta').outerHeight(true)-25 + 'px'});
    }

	$('a#show_hide_footer').click(function() {
		if ($(this).next().height() > 5) {
			$(this).next().animate({'height' : '0px'});
            $(this).text('+');
            $('body').css({'padding-bottom' : '0px'});
			$.cookie('cc_CLOSED_FOOTER', 'true', { expires: 365, path: '/' } );
		} else {
			$(this).next().animate({'height' : '155px'});
            $(this).text('-');
            $('body').css({'padding-bottom' : '155px'});
            $.cookie('cc_CLOSED_FOOTER', 'false', { expires: 365, path: '/' } );
		}
		return false;
	});

	$('div.listchildren ul.showarrows').each( function() {
		if ($(this).children().length > 7) {
			$(this).parent().append('<a class="arrow_down_list" href="#">scroll down</a>');
			$(this).before('<a class="arrow_up_list" href="#">scroll up</a>');
			$('a.arrow_up_list').hide();
			$(this).css({'height' : '390px'});
		}
	});

    $('article.article_teampanel, section#section_teamcarousel').each( function() {
		$(this).css({'background-image' : 'url(/etc/designs/cc/images/blurred_bg_' + (1 + Math.floor(Math.random() * 6)) + '.jpg)'});
		if ($(this).find('article.article_teamcarousel').length == 1) {
			$(this).find('.a_teamcarousel_left').hide();
			$(this).find('.a_teamcarousel_right').hide();
		}
	});
	

    $('article.article_stack_style_8 a.a_standardlink_small').on('click', function() {
		imageTextBlockShowDetail($(this));
		return false;
	});

    $('article.article_stack_style_8 a.a_standardlink').on('click', function() {
		imageTextBlockHideDetail($(this));
		return false;
	});
	
	$('a.arrow_up_list').on('click', function() {
		$(this).parent().children('ul').animate({scrollTop: '-=53px'});
		return false;
	});

    $('body').on('click', 'a.a_openimage', function(e) {
		openImage($(this).attr('href'));
		e.preventDefault();
	});

    $('body').on('click', 'a#a_closeimage', function(e) {
        $(this).parent().fadeOut( function() {
			$(this).remove();
        });
		e.preventDefault();
	});

	$('a.arrow_down_list').on('click', function() {
		//alert('clicked');
		$('a.arrow_up_list').slideDown();
		$(this).prev().animate({scrollTop: '+=53px'});
		return false;
	});
	
	$('a.a_standardlink').each( function() {
		//alert($(this).css('background-color'));
		if ($(this).css('background-color') == '#FFD800' || $(this).css('background-color') == 'rgb(255, 216, 0)') {
			//alert('yes');
			$(this).addClass('no_border');
		}
	});
	
	$('ul li a.latest_briefings').click( function() {
		$('article.latest_briefings').slideDown();
		$('article.featured_briefings').slideUp();
		$(this).parent().parent().stop().animate({'background-position-x' : '-760px'});
		return false;
	});
	
	$('ul li a.featured_briefings').click( function() {
		$('article.featured_briefings').slideDown();
		$('article.latest_briefings').slideUp();
		$(this).parent().parent().stop().animate({'background-position-x' : '-920px'});
		return false;
	});
	
	// Call the iframe resizer 
	resizeIframe();

	
	// Ensure Search Box clears content when focussed
	$('#headersearchformQuery').focus( function() {
        placeholderFormTextFOCUS($(this), 'Type to search');
	});
		
	// Reset it on blur
	$('#headersearchformQuery').blur( function() {
		placeholderFormTextBLUR($(this), 'Type to search');
	});
	
	/*$('form.form_search').submit( function(e) {
	// alert($('#headersearchformQuery').val());
		if ($('#headersearchformQuery').val('Type to search')) {
		} else {
			$('form.form_search').submit();
		}
		return false;
		
	});*/

    // Ensure Search Box clears content when focussed
	$('form.form_filter_search input.query').focus( function() {
        placeholderFormTextFOCUS($(this), 'Find a lawyer');
	});

	// Reset it on blur
	$('form.form_filter_search input.query').blur( function() {
		placeholderFormTextBLUR($(this), 'Find a lawyer');
	});

	$('form.form_filter_search_nav input#query_nav').blur( function() {
		placeholderFormTextBLUR($(this));
	});


	$('a#a_back_to_top').click( function() {
		backToTop();
	});

	
	// OSP CLICK FUNCTION (TRIGGERED ON FOCUS ON DESKTOP MACHINES FOR ACCESSIBILITY PURPOSES)
	if ($(window).width() < 1300) {	
	
		$('a#a_tkosp_button').click( function(e) {
			openCloseTKOSP();
            e.preventDefault();
		});
		
	} else {

		/*

		$('a#a_tkosp_button').click( function(e) {
			openCloseTKOSP();
            e.preventDefault();
		});

        */
		
		$('a#a_tkosp_button').focus( function(e) {
			openCloseTKOSP();
			 e.preventDefault();
		});
	}
	
	reorderBlogArticles($('article.article_latest_briefings ul.ul_latest_briefings'));
    copyTags($('article.article_latest_briefings ul.ul_filter_list'));
	
	$('article.article_latest_briefings ul.ul_filter_list').on('click', 'li.li_taglist_resource a', function() {
		//alert('clicked');
		filterResources($(this));
		$('p.p_more_briefings a').hide();
		return false;
	});
	
	$('article.article_latest_briefings > ul.ul_latest_briefings').each( function(i) {
		$(this).children('li').each( function(ii) {
			if (ii > 4) {
				$(this).hide();
			}
		});
	});
	
	$('div.listarticlessix ul li').each( function(i) {
		//alert(i);
		if (i > 5) {
			$(this).hide();
		} else {
			//$('div.listarticlessix a.arrow_right').hide();
		}
	});
	
	if ($('div.listarticlessix ul').children().length < 6) {
		$('div.listarticlessix a.arrow_right').hide();
	}
	
	$('p.p_more_briefings a').not('p.p_more_briefings_static a').on('click', function() {
		$('article.article_latest_briefings ul.ul_latest_briefings > li:visible').next().slideDown();
		$('article.article_latest_briefings ul.ul_latest_briefings > li:visible').next().slideDown();
		$('article.article_latest_briefings ul.ul_latest_briefings > li:visible').next().slideDown();
		$('article.article_latest_briefings ul.ul_latest_briefings > li:visible').next().slideDown();
		$('article.article_latest_briefings ul.ul_latest_briefings > li:visible').next().slideDown();
		if ($('article.article_latest_briefings ul.ul_latest_briefings > li:last-child').is(':visible')) {
			$(this).slideUp();
		}
		return false;
	});
	
	$('div.listarticlessix a.arrow_right').on('click', function() {
		$('div.listarticlessix ul li:visible').next().slideDown();
		$('div.listarticlessix ul li:visible').next().slideDown();
		$('div.listarticlessix ul li:visible').next().slideDown();
		$('div.listarticlessix ul li:visible').next().slideDown();
		$('div.listarticlessix ul li:visible').next().slideDown();
		$('div.listarticlessix ul li:visible').next().slideDown();
		if ($('div.listarticlessix ul li:last-child').is(':visible')) {
			$(this).slideUp();
		}
		return false;
	});
	
	$('div.jumpmenu select').on('change', function() {
		//alert($(this).val());
		
		window.location = $(this).val();
	});
	
	// -------------------------------------------------------------------------------------
	// Standard grey tab initialisation
	// -------------------------------------------------------------------------------------
	
	// Start by data marking all the corresponding tabs and their targets
	$('section#section_tabbed_content ul#ul_article_greytabs').each( function() {
		$(this).find('li a').each( function(i) {
			$(this).addClass('tab_' + i);
		});
		$(this).parent().find('article.article_greytabs').each( function(i) {
			$(this).addClass('tab_' + i);
			// Hide the articles we don't need in the first view
			if (i > 0) {
				$(this).hide();	
			}
		});
		$(this).after('<img class="img_up_arrow_generic" src="/etc/designs/cc/images/arrow_up_generic.png" width="30" height="15" alt="" />');
		$(this).next().animate({
			'margin-left': (($(this).children('li:first-child').position().left + ($(this).children('li:first-child').width() / 2)) - 15) + 'px'
		});
	});
	
	// Start by data marking all the corresponding aside tabs and their targets
	$('section.section_tabbed_content ul.ul_article_greytabs li a').each( function(i) {
		$(this).addClass('tab_' + i);
	});
	$('section.section_tabbed_content article.article_greytabs').each( function(i) {
		$(this).addClass('tab_' + i);
		// Hide the articles we don't need in the first view
		if (i > 0) {
			$(this).hide();	
		}
	});
	
	// Give the tabs some click functionality
	$('section#section_tabbed_content ul#ul_article_greytabs li a').click( function(e) {


		
		$(this).parent().parent().next().animate({
			'margin-left': (($(this).parent().position().left + ($(this).parent().width() / 2)) - 15) + 'px'
		});
		
		$(this).parent().parent().parent().find('article.article_greytabs').slideUp();
		$(this).parent().parent().parent().find('article.' + $(this).attr('class')).slideDown();
		
		if ($(this).parent().hasClass('activeTab')) {
			$(this).parent().parent().animate({'background-position' : '-255px'});
		} else {
			$(this).parent().parent().animate({'background-position' : '-70px'});
		}
		e.preventDefault();
		
	});
	
	// Give the aside tabs some click functionality
	$('section.section_tabbed_content ul.ul_article_greytabs li a').click( function(e) {
		
		$('section.section_tabbed_content article.article_greytabs').slideUp();
		$('section.section_tabbed_content article.' + $(this).attr('class')).slideDown();
		
		if ($(this).parent().hasClass('activeTab')) {
			//alert('yes');
			$(this).parent().parent().animate({'background-position' : '-255px'});
		} else {
			$(this).parent().parent().animate({'background-position' : '-70px'});
			//alert('no');
		}
		e.preventDefault();
		
	});

    /*
    // Give the profile tabs some click functionality
	$('section.section_relevantexperince > div > a.arrow_right').click( function(e) {
		$(this).slideUp();
        $(this).prev().children().slideDown();
		e.preventDefault();
	});
    */

	$('div.profile.section div.parsyscol1 ul.ul_article_greytabs_generic li a').click( function(e) {

        $('section.section_profile_tab').slideUp();
		$('section.' + $(this).attr('class')).slideDown();
		
		if ($(this).parent().hasClass('activeTab')) {
			$(this).parent().parent().animate({'background-position' : (($(this).parent().position().left - 1000) + ($(this).parent().width() / 2)) + 'px'});
		} else {
            $(this).parent().parent().animate({'background-position' : (($(this).parent().position().left - 1000) + ($(this).parent().width() / 2)) + 'px'});

		}
		e.preventDefault();
	});

    if ($('a.section_relevantexperince').length == 0) {
		$('a.section_publicationsandinsights').trigger('click');
    }

	// -------------------------------------------------------------------------------------
	// Control careers block forms
	// -------------------------------------------------------------------------------------

    $('input.input_submit_careers').click( function(e) {
        if ($(this).prev().prev().val() == '') {
			$(this).prev().slideDown();
		} else {
			$(this).prev().slideUp( function() {
				$(this).parent().submit();	
			});
		}
		e.preventDefault();
	});
	
	$('div.keypoints section.section_article_accordion article').click( function() {
		//alert('clicked'); 
		var thisElement = $(this);
		var widthOfContainer = (14.2 * ($(this).parent().children('article').length + 2));
		var widthOfKeyPoint = 100 / ($(this).parent().children('article').length + 2);
		var widthOfOpenKeyPoint = (widthOfKeyPoint * 3) - 1;
		//alert(widthOfContainer);
		if ($(this).parent().children('article').length > 5) {
		$('div.keypoints section.section_article_accordion').css({'width' : widthOfContainer + '%'})
		}
		$('div.keypoints section.section_article_accordion article').stop().animate({'width' : widthOfKeyPoint + '%'});
		$('div.keypoints section.section_article_accordion article section').slideUp();
		$('div.keypoints section.section_article_accordion article h4').stop().animate({'font-size' : '40px', 'line-height' : '46px'});
		$('div.keypoints section.section_article_accordion article h5').stop().animate({'font-size' : '20px', 'line-height' : '28px'});
		$(this).stop().animate({'width' : widthOfOpenKeyPoint + '%'}, function(){
			$(this).children('section').slideDown();
			$('div.keypoints').animate({scrollLeft: (thisElement.prev().position().left)});
		});
		$(this).children('h4').stop().animate({'font-size' : '80px', 'line-height' : '92px'});
		$(this).children('h5').stop().animate({'font-size' : '40px', 'line-height' : '45px'});
	});
	
	$('div.keypoints section.section_article_accordion article:first').addClass('first_article').trigger('click');
	
	$('div.keypoints section.section_article_accordion').each( function() {
		if ($(this).children('article').length < 3) {
			$(this).children().addClass('open').unbind('click'); 
		}
	});
	
	$('div.accordionflexible h4 a').click( function(){
		$(this).parent().next().slideToggle();
		return false;
	});
	
	$('div.accordionflexible h4.pre-open a').trigger('click');

	
	$('map#map_pie area').each( function(i) {
		$(this).click( function() { 
			//alert('click');
			//$('#img_pie').attr('src','/etc/designs/cc/images/pie-inner-' + (i + 1) + '.png');
			$('img.img_pie_base_animate').stop().animate({'top' : '200px', 'left' : '170px', 'width' : '0px', 'height' : '0px', 'opacity' : '0'});
			$('img.img_pie_base_' + (i + 1)).stop().animate({'top' : '-40px', 'left' : '-80px', 'width' : '500px', 'height' : '500px', 'opacity' : '1'});
		return false;
		});
	});

    $('section.section_awardsandcitations div.div_awards_container').each( function(i) {
        if ($(this).find('ul li').length > 1) {
            $(this).find('ul li').each( function(ii) {
                $(this).parent().parent().next().append('<li><a aria-label="Award Section List Icons" data-award="' + ii + '" href="#"></a></li>');
                $(this).parent().parent().next().find('li:first-child a').addClass("selected");
            });
        } else{
            console.log($(this).next().hide());
        }
    });

    $('section.section_awardsandcitations ul.ul_awardsandcitations').on('click','li a', function() {
	$('section.section_awardsandcitations ul.ul_awardsandcitations li a').removeClass('selected');
        $(this).addClass('selected');
        var nMoveToAward = ($(this).parent().parent().parent().width() + 20) * parseInt($(this).data('award'));
        $(this).parent().parent().prev().animate({'margin-left' : '-' + nMoveToAward + 'px'});
        return false;
     });

    // -------------------------------------------------------------------------------------
	// Podcast initialisation
	// -------------------------------------------------------------------------------------

    var input = document.querySelector("input[class=rangeColor]");
    if(input!=null){
        document.documentElement.style.setProperty('--color', "#"+input.name);
    }


    $('audio.audio_podcast').each( function() {

		var ccaudioplayerJQ = $(this);
        var ccaudioplayer = $(this)[0];
        var ccprogressbar = $(this).next().next();
        var cccontrols = ccprogressbar.next().next();
        var ccprogresscontrol = ccprogressbar.next();
        var ccduration = 0;
        var cccurrenttime = 0;
        var ccpercentcomplete = 0;
        var inputProgressBar = $(this).prev();
        // ccaudioplayer.onloadeddata = function() {
        $(this).on('loadeddata', function() {

            ccduration = ccaudioplayer.duration;
    		cccontrols.find('li.li_podcast_current_time').text(formatSeconds(cccurrenttime));
            cccontrols.find('li.li_podcast_total_time').text(formatSeconds(ccduration));

            var currenttime = inputProgressBar.val();
            var pos = (currenttime) * 100 / 1000 + '% 100%';
            inputProgressBar.css("background-size",pos);
            inputProgressBar.on('input change',function(){
                var timecccurrentupdate = (inputProgressBar.val()/ 1000);
                var inputPosition = (inputProgressBar.val()) * 100 / 1000 + '% 100%';
                inputProgressBar.css("background-size",inputPosition);
                ccaudioplayer.currentTime = ccduration*timecccurrentupdate;
                cccontrols.find('li.li_podcast_current_time').text(formatSeconds(ccaudioplayer.currentTime));
                cccontrols.find('li.li_podcast_total_time').text(formatSeconds(ccduration));
            })

            ccaudioplayer.ontimeupdate = function() {

				cccurrenttime = ccaudioplayer.currentTime;
                ccpercentcomplete = cccurrenttime / ccduration * 100;
                //ccprogressbar.stop().animate({'width': ccpercentcomplete + '%'});
                cccontrols.find('li.li_podcast_current_time').text(formatSeconds(cccurrenttime));
                cccontrols.find('li.li_podcast_total_time').text(formatSeconds(ccduration));
                var inputPosition = ccpercentcomplete + '% 100%';
                inputProgressBar.css("background-size",inputPosition);
                inputProgressBar.val((ccaudioplayer.currentTime/ccduration)*1000);

				if (parseInt(ccpercentcomplete) > 99) {
					console.log(ccaudioplayerJQ.data('aapagename') + '|' + ccaudioplayerJQ.data('aacompname') + '|' + ccaudioplayerJQ.data('aamaintitle') + '|' + ccaudioplayerJQ.data('aalocation') + '|Podcast|Podcast Completed');
                	linkClick(ccaudioplayerJQ.data('aapagename') + '|' + ccaudioplayerJQ.data('aacompname') + '|' + ccaudioplayerJQ.data('aamaintitle') + '|' + ccaudioplayerJQ.data('aalocation') + '|Podcast|Podcast Completed');
                }
            };

//            ccprogresscontrol.click( function(e) {
//                var posX = e.pageX - $(this).offset().left;
//                var posXasPercentage = posX / cccontrols.outerWidth(true) * 100;
//                ccaudioplayer.currentTime = ccduration * (posXasPercentage / 100);
//                e.preventDefault();
//            });

            ccaudioplayer.volume = 0.5;

            ccaudioplayer.ended = function() {
                console.log(ccaudioplayerJQ.data('aapagename') + '|' + ccaudioplayerJQ.data('aacompname') + '|' + ccaudioplayerJQ.data('aamaintitle') + '|' + ccaudioplayerJQ.data('aalocation') + '|Podcast|Podcast Completed');
                linkClick(ccaudioplayerJQ.data('aapagename') + '|' + ccaudioplayerJQ.data('aacompname') + '|' + ccaudioplayerJQ.data('aamaintitle') + '|' + ccaudioplayerJQ.data('aalocation') + '|Podcast|Podcast Completed');

            };

        });
        // }

        cccontrols.find('a.a_podcast_play').click( function(e) {

			if (ccaudioplayer.paused) {
				ccaudioplayer.play();
                console.log(ccaudioplayerJQ.data('aapagename') + '|' + ccaudioplayerJQ.data('aacompname') + '|' + ccaudioplayerJQ.data('aamaintitle') + '|' + ccaudioplayerJQ.data('aalocation') + '|Podcast|Podcast Play');
                linkClick(ccaudioplayerJQ.data('aapagename') + '|' + ccaudioplayerJQ.data('aacompname') + '|' + ccaudioplayerJQ.data('aamaintitle') + '|' + ccaudioplayerJQ.data('aalocation') + '|Podcast|Podcast Play');
            } else {
				ccaudioplayer.pause();
                console.log(ccaudioplayerJQ.data('aapagename') + '|' + ccaudioplayerJQ.data('aacompname') + '|' + ccaudioplayerJQ.data('aamaintitle') + '|' + ccaudioplayerJQ.data('aalocation') + '|Podcast|Podcast Pause');
                linkClick(ccaudioplayerJQ.data('aapagename') + '|' + ccaudioplayerJQ.data('aacompname') + '|' + ccaudioplayerJQ.data('aamaintitle') + '|' + ccaudioplayerJQ.data('aalocation') + '|Podcast|Podcast Pause');
            }

			$(this).parent().toggleClass('li_podcast_paused');
			$(this).parent().parent().parent().find('a.a_event_trigger_play');

            e.preventDefault();

        });

        cccontrols.find('a.a_podcast_15_plus').click( function(e) {
            ccaudioplayer.currentTime = ccaudioplayer.currentTime + 15;
            e.preventDefault();
        });

        cccontrols.find('a.a_podcast_15_minus').click( function(e) {
            ccaudioplayer.currentTime = ccaudioplayer.currentTime - 15;
            e.preventDefault();
        });

        // Hide all "Next Profile" buttons on the podcast comp
        cccontrols.find('li.li_podcast_next a').hide();
        // Loop over them to find the "next" one
        cccontrols.find('li.li_podcast_next a').each( function(i) {
        	var sThisURL = $(this).attr('href');
        	if (document.location.href.indexOf(sThisURL) > -1) {
        		$(this).next().show().parent().css({'opacity': '1.0', 'height': 'auto'});
            	return false;	
        	}
		});
    
        // Hide all "Prev Profile" buttons on the podcast comp
        cccontrols.find('li.li_podcast_prev a').hide();
        // Loop over them to find the "next" one
        cccontrols.find('li.li_podcast_prev a').each( function(i) {
        	var sThisURL = $(this).attr('href');
            if (document.location.href.indexOf(sThisURL) > -1) {
            	$(this).prev().show().parent().css({'opacity': '1.0', 'height': 'auto'});
				return false;
			}
		});

		$(this).parent().find($('a.a_podcast_slider')).draggable({
            containment: 'parent', 
            axis: 'x', 
            drag: function() {
                ccaudioplayer.volume = parseInt($(this).css('left')) / $(this).parent().width();
            },
        });

        $(this).parent().find($('a.a_podcast_slider')).on('click touchmove', function(e) {
			e.preventDefault();
        });

        $(this).parent().find($('a.a_podcast_slider')).on('touchstart', function(e) {
			alert('Please use the volume controls on your device to adjust the volume.');
        });

    });

    function formatSeconds(seconds) {
		return (new Date(seconds * 1000)).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0];
	}

	// -------------------------------------------------------------------------------------
	// GEO LOCATION FEATURES
	// -------------------------------------------------------------------------------------

    getGeoLocation();

    // -------------------------------------------------------------------------------------
	// RELATED CONTENT FEATURES
	// -------------------------------------------------------------------------------------

    $('section.section_related_content h2 a').click(function() {
        getRelatedContent($(this));
        return false;
    });

    $('div.latestrelatedcontent section.section_related_content:first h2 a').trigger('click');

});

$(window).on("load", function() {
    var tallestChildVideo = 0;
        $('.video-card').each(function(){
            if (tallestChildVideo <= $(this).height()) {
                tallestChildVideo = $(this).height();
            }
        });
    $('.video-card').css({'height': tallestChildVideo+24 + 'px'});

	headerCarousel($('header#header_marquee div.page_container').width());
	
	layoutResize();
	$('li.li_carousel_0 a').addClass('selected');

	
	//Carousel Navigation
	$('a.carousel_prev').on('click', function() {
		//alert('clicked');
		if ($(this).parent().prev().find('a.selected').parent().prev().length == 0) {
			//alert('yes');
			$(this).parent().prev().find('li:last-child').children().trigger('click');
		} else {
			$(this).parent().prev().find('a.selected').parent().prev().children().trigger('click');
		}
		if($(this).parent().prev().find('a.selected').children().attr('class') == "whiteCopy_List"){
            $(this).parent().children('.carousel_prev').children().css("filter","grayscale(1) invert(1)");
            $(this).parent().children('.carousel_next').children().css("filter","grayscale(1) invert(1)");
        } else{
            $(this).parent().children('.carousel_prev').children().css("filter","grayscale(1) invert(0)");
            $(this).parent().children('.carousel_next').children().css("filter","grayscale(1) invert(0)");
        }
		return false;
	});
		
	$('a.carousel_next').on('click', function() {
			//alert('clicked');
		if ($(this).parent().prev().find('a.selected').parent().next().length == 0) {
			//alert('yes');
			$(this).parent().prev().find('li:first-child').children().trigger('click');
		} else {
			$(this).parent().prev().find('a.selected').parent().next().children().trigger('click');
		}

		if($(this).parent().prev().find('a.selected').children().attr('class') == "whiteCopy_List"){
            $(this).parent().children('.carousel_prev').children().css("filter","grayscale(1) invert(1)");
            $(this).parent().children('.carousel_next').children().css("filter","grayscale(1) invert(1)");
        } else{
            $(this).parent().children('.carousel_prev').children().css("filter","grayscale(1) invert(0)");
            $(this).parent().children('.carousel_next').children().css("filter","grayscale(1) invert(0)");
        }
		return false;
	});
	
	$('div.div_teamcarousel_container_carrier article.article_teamcarousel:first').addClass('selected');
	
	$('a.a_teamcarousel_left').on('click', function() {
		if ($('div.div_teamcarousel_container_carrier article.article_teamcarousel:first').hasClass('selected')) {

			$('div.div_teamcarousel_container_carrier article.article_teamcarousel.selected').removeClass('selected');
			$('section#section_teamcarousel.section_teamcarousel_group div.div_teamcarousel_image_container div.selected').removeClass('selected');
			
			$('div.div_teamcarousel_container_carrier').animate({'left' : '-' + (100 * ($('div.div_teamcarousel_container_carrier').children().length - 1)) + '%'});
			$('div.div_teamcarousel_container_carrier article.article_teamcarousel:last').addClass('selected');
			$('section#section_teamcarousel.section_teamcarousel_group div.div_teamcarousel_image_container div:last').addClass('selected');
			
		} else {
			$('div.div_teamcarousel_container_carrier article.article_teamcarousel.selected').removeClass('selected').prev().addClass('selected');
			$('section#section_teamcarousel.section_teamcarousel_group div.div_teamcarousel_image_container div.selected').removeClass('selected').prev().addClass('selected');
			$('div.div_teamcarousel_container_carrier').animate({'left' : '+=100%'});
		}
		return false;
	});
	
	$('a.a_teamcarousel_right').on('click', function() {
		if ($('div.div_teamcarousel_container_carrier article.article_teamcarousel:last').hasClass('selected')) {
			$('div.div_teamcarousel_container_carrier article.article_teamcarousel.selected').removeClass('selected');
			$('section#section_teamcarousel.section_teamcarousel_group div.div_teamcarousel_image_container div.selected').removeClass('selected');
			
			$('div.div_teamcarousel_container_carrier').animate({'left' : '0px'});
			$('div.div_teamcarousel_container_carrier article.article_teamcarousel:first').addClass('selected');
			$('section#section_teamcarousel.section_teamcarousel_group div.div_teamcarousel_image_container div:first').addClass('selected');
		} else {
			$('div.div_teamcarousel_container_carrier article.article_teamcarousel.selected').removeClass('selected').next().addClass('selected');
			$('section#section_teamcarousel.section_teamcarousel_group div.div_teamcarousel_image_container div.selected').removeClass('selected').next().addClass('selected');
			$('div.div_teamcarousel_container_carrier').animate({'left' : '-=100%'});
		}
		return false;
	});
		
	

    $('ul.ul_carousel_nav li').on('click', 'a', function() {
            //alert(parseInt($(this).text()));
        $(this).parent().parent().children().children('a').removeClass('selected');
        $(this).addClass('selected');
        $(this).parent().parent().parent().next().slideDown();
        $(this).parent().parent().parent().next().children('div.div_carousel_container_carrier').stop().animate({'left' : '-' + (100 * parseInt($(this).text())) + '%'});

        $(this).parent().parent().parent().children('#div_header_carousel div.parsysheadercarousel').stop().animate({'left' : '-' + (100 * parseInt($(this).text())) + '%'});

        if ($(this).parent().parent().parent().parent().hasClass('carousel_style_3')) {

            $('main#main_content div.div_carousel_container.carousel_style_3 nav.nav_carousel img').stop().animate({'left' : ($(this).position().left + ($(this).width() / 2)) - 18 + 'px'});

            $('main#main_content div.div_carousel_container.carousel_style_3 nav.nav_carousel ul li a').stop().animate({'color' : '#999999'});
            $(this).stop().animate({'color' : '#41a5d8'});

        }

        if($(this).children().attr('class') == "whiteCopy_List"){
			$(this).parent().parent().parent().next().children('.carousel_prev').children().css("filter","grayscale(1) invert(1)");
            $(this).parent().parent().parent().next().children('.carousel_next').children().css("filter","grayscale(1) invert(1)");
        } else{
			$(this).parent().parent().parent().next().children('.carousel_prev').children().css("filter","grayscale(1) invert(0)");
            $(this).parent().parent().parent().next().children('.carousel_next').children().css("filter","grayscale(1) invert(0)");
        }

        return false;
    });

    $('ul.ul_carousel_nav a.previous_arrow').on('click', function() {
        if($('ul.ul_carousel_nav li a.selected').parent().prev().attr('class') != "previous_arrow"){

            $(this).parent().find('a.selected').removeClass('selected').parent().prev().children().addClass('selected');
            $(this).parent().parent().next().children('div.div_carousel_container_carrier').stop().animate({'left' : '-' + (100 * parseInt($(this).parent().find('a.selected').children().text())) + '%'});

            $(this).parent().parent().children('#div_header_carousel div.parsysheadercarousel').stop().animate({'left' : '-' + (100 * parseInt($(this).parent().find('a.selected').children().text())) + '%'});
        }

        if($('ul.ul_carousel_nav li a.selected').parent().prev().attr('class') == "previous_arrow"){
            $('ul.ul_carousel_nav a.previous_arrow').children().removeClass('previous_arrow_image');
        } else{
            $('ul.ul_carousel_nav a.previous_arrow').children().addClass('previous_arrow_image');
        }
        return false;
    });

    $('ul.ul_carousel_nav a.next_arrow').on('click', function() {
        if($('ul.ul_carousel_nav li a.selected').parent().next().attr('class') != "next_arrow"){

            $(this).parent().find('a.selected').removeClass('selected').parent().next().children().addClass('selected');
            $(this).parent().parent().next().children('div.div_carousel_container_carrier').stop().animate({'left' : '-' + (100 * parseInt($(this).parent().find('a.selected').children().text())) + '%'});

            $(this).parent().parent().children('#div_header_carousel div.parsysheadercarousel').stop().animate({'left' : '-' + (100 * parseInt($(this).parent().find('a.selected').children().text())) + '%'});
        }

        if($('ul.ul_carousel_nav li a.selected').parent().next().attr('class') == "next_arrow"){
            $('ul.ul_carousel_nav a.next_arrow').children().removeClass('next_arrow_image');
        } else{
            $('ul.ul_carousel_nav a.next_arrow').children().addClass('next_arrow_image');
        }
        return false;
    });

    $('ul.ul_carousel_nav a.previous_arrow').hover( function() {
        if($('ul.ul_carousel_nav li a.selected').parent().prev().attr('class') == "previous_arrow"){
            $('ul.ul_carousel_nav a.previous_arrow').children().removeClass('previous_arrow_image');
        } else{
            $('ul.ul_carousel_nav a.previous_arrow').children().addClass('previous_arrow_image');
        }
    });

    $('ul.ul_carousel_nav a.next_arrow').hover( function() {
        if($('ul.ul_carousel_nav li a.selected').parent().next().attr('class') == "next_arrow"){
            $('ul.ul_carousel_nav a.next_arrow').children().removeClass('next_arrow_image');
        } else{
            $('ul.ul_carousel_nav a.next_arrow').children().addClass('next_arrow_image');
        }
    });

    $('div.parsysheadercarousel').on('swipeleft', function(){
        $('ul.ul_carousel_nav a.next_arrow').trigger('click');
    });

    $('div.parsysheadercarousel').on('swiperight', function(){
        $('ul.ul_carousel_nav a.previous_arrow').trigger('click');
    });
    var startPoint = 0;
    $('div.parsysheadercarousel').on('touchstart', function(e){
        startPoint = e.originalEvent.changedTouches[0].clientX;
    });
    $('div.parsysheadercarousel').on('touchend', function(e){
        if(e.originalEvent.changedTouches[0].clientX < startPoint){
            $('ul.ul_carousel_nav a.next_arrow').trigger('click');
        } else if(e.originalEvent.changedTouches[0].clientX > startPoint){
            $('ul.ul_carousel_nav a.previous_arrow').trigger('click');
        }
    });

    var startPoint_carouselContainer = 0;
    $('div.parsyscarousel.parsys').on('touchstart', function(e){
        startPoint_carouselContainer = e.originalEvent.changedTouches[0].clientX;
    });
    $('div.parsyscarousel.parsys').on('touchend', function(e){
        if($(this).parent().parent().parent().hasClass('carousel_style_1')){
            if(e.originalEvent.changedTouches[0].clientX < startPoint_carouselContainer){
                $(this).parent().next().next().trigger('click');
            } else if(e.originalEvent.changedTouches[0].clientX > startPoint_carouselContainer ){
                $(this).parent().next().trigger('click');
            }
        }
    });

    /*
	$('article.article_container article.article_imagetextblock_pannel').on('click', function() {
		var thisLink = $(this).children().find('a.a_standardlink').attr('href');
        if ($(this).children().find('a.a_standardlink').hasClass('a_openimage')) {
			openImage(thisLink);
        } else {
			window.location.href = thisLink;
        }
	});
    */

	$('div.div_panel_container div.imagetextblock article.article_imagetextblock').on('click', function() {
        //alert('clicked');
		var thisLink = $(this).find('a.a_standardlink').attr('href');
		//alert(thisLink);
		window.location.href = thisLink;
	});
	
	var triggerMarquee = function(){
        //clearInterval(checkInterval);
        if ($('header#header_marquee ul.ul_carousel_nav li a.selected').parent().next().length == 0 && $('header#header_marquee ul.ul_carousel_nav li a.selected').parent().next().attr('class') != "next_arrow") {
            $('header#header_marquee ul.ul_carousel_nav li.li_carousel_0 a').trigger('click');
        } else if($('header#header_marquee ul.ul_carousel_nav li a.selected').parent().next().attr('class') != "next_arrow") {
            $('header#header_marquee ul.ul_carousel_nav li a.selected').parent().next().children().trigger('click');
        } else{
            $('header#header_marquee ul.ul_carousel_nav li.li_carousel_0 a').trigger('click');
        }
    }
	var triggerMarqueeInterval = setInterval( function(){triggerMarquee()}, 3500);
		
	$('header ul.ul_carousel_nav li a').focus( function() {
		clearInterval(triggerMarqueeInterval);
	});



});

$(window).resize( function() {
	layoutResize();
});


$(window).scroll( function() {
    clearTimeout($.data(this, 'scrollTimer'));
    $.data(this, 'scrollTimer', setTimeout(function() {
        checkArticleInView();
   		ArticleParallax();
    }, 10));
});


// ===================================================================================
// FUNCTIONS


function checkArticleInView() {
    //alert('out of view');
    $('article.article_animate_style_1, article.article_animate_style_2').each( function() {
        if (($(this).offset().top - $(window).scrollTop()) < ($(window).height())) {
			$(this).removeClass('outofview');
			if (!$(this).hasClass('article_nobackgroundcolour')) {
            	$(this).css({'background-color': $(this).children('div.div_imagetextblock_textcontainer').css('background-color')});
            }
        } else {
			$(this).addClass('outofview');
            $(this).css({'background-color': '#FFFFFF;'});
        }
    });
}

function ArticleParallax() {
    $('article.article_parallax').each( function() {
        $(this).find('img').css({'margin-bottom' : -15 + (($(this).offset().top - $(window).scrollTop()) / 50) + '%'});
        $(this).find('img').css({'margin-top' : -15 - (($(this).offset().top - $(window).scrollTop()) / 50) + '%'});

       	if ($(this).hasClass('article_stack_style_12') || $(this).hasClass('article_stack_style_13')) {
			$(this).find('div.div_imagetextblock_textcontainer').css({'margin-top' :  (($(this).offset().top - $(window).scrollTop()) / 50) + '%'});
        }

    });

}


// Function to bring together related resizing and layout commands that need doing on load and resize
function layoutResize() {
	


	resizeCarousel();
	lockOnResize = 1;
	
	// Call the iframe resizer
	resizeIframe();
	resizeCarousel();
	
	// Call the skimmer once to set up the page correctly

	equaliseHeights($('article.article_skim'));
	
	equaliseHeights($('div.div_panel_container ul li a'));
	
	equaliseHeights($('div.listarticlessix ul li'));
	
	equaliseHeights($('article.article_teampanel_small'));

	equaliseHeights($('main#main_content article.article_container article.article_imagetextblock_pannel'));
	
	equaliseHeights($('div.podcastlibrary > article > ul > li'));
	
	//equaliseHeights($('article.article_aside_contact_small'));
	
	// Loop over the skimmable objects and group them together top position
	$('article.article_skim').each( function() {
		var thisOffset = Math.round($(this).offset().top);
		$(this).addClass('offset_top_' + thisOffset);
		equaliseHeights($('article.article_skim.offset_top_' + thisOffset));
	});
	
	$('div.div_panel_container ul li a').each( function() {
		var thisOffset = Math.round($(this).offset().top);
		$(this).addClass('offset_top_' + thisOffset);
		equaliseHeights($('div.div_panel_container ul li a.offset_top_' + thisOffset));
	});
	
	
	$('header#header_marquee div.parsysheadercarousel article.article_imagetextblock').each( function() {
		$(this).css('width', $('header#header_marquee div.page_container').width());
	});

    $('section.section_awardsandcitations div.div_awards_container ul li').each( function(i) {
        $(this).css({'width' : $('section.section_awardsandcitations').width()});
    });
		
}

function resizeCarousel() {
	
	$('div.div_teamcarousel_container_carrier').each( function() {
		var thisElement = $(this)
		var countChildren = $(this).find('.article_teamcarousel').length;
		
		$(this).find('.article_teamcarousel').each( function(i) {
			 $(this).css({'max-width' : 100 / countChildren + '%'});
		 });
		$(this).css({'width' : 100 * countChildren + '%'});
	});
	
	//alert('active');
	$('div.div_carousel_container_carrier').each( function() {
		//alert('active');
		
		var thisElement = $(this)
		var countChildren = $(this).find('.article_imagetextblock').length;
		var tallestChild = 0;
		var nExtraArticle = 0;
		
		
		
		// Check that this parents parent has class of 'carousel_style_2' and if it does take off the 'article_imagetextblock' from all of the children articles so that we can restyle the articles and contain them in an outer container of 'article_imagetextblock' to avoid a big block of overiding css with to many '!important's and not altering the jquery that we have worked very hard on as it is so great and solid and perfect...
		if ($(this).parent().parent().hasClass('carousel_style_2')) {
			
			nExtraArticle = 3 - (countChildren % 3);


			if (nExtraArticle < 3) {
				for (i = 0; i < nExtraArticle; i++) {
				//alert('no');
					$('div.div_carousel_container_carrier').children().append('<article class="article_imagetextblock" style="display: none;"></article>');
				}
			}
			//alert('yes');
			if ($(this).find('.article_container').length == 1) {
				//alert($(this).attr('class'));
				$('.carousel_arrow').hide();
			}
			 var countArticles = 0;
			 $(this).find('.article_imagetextblock').not('.article_container').each( function(i) {
				// alert('working');
				 //alert(countArticles);
				 $(this).removeClass('article_imagetextblock').addClass('article_imagetextblock_pannel').addClass('group');
				 if (countArticles == 2) {
					// alert(countArticles);
					 $('.article_imagetextblock_pannel.group').wrapAll('<article class="article_container"></article>');
					 $('.article_imagetextblock_pannel').removeClass('group');
					 countArticles = 0;
				 } else {
					 //alert(countArticles);
					 countArticles += 1;
				 }
				
				
			 });
			
			$('.article_container').addClass('article_imagetextblock');
			$('.article_container').each( function() {
				var thisElement = $(this);
				tallestChildPannel = 0;
				$(this).children('.article_imagetextblock_pannel').each( function(i) {
					//alert('works');
					$(this).css('height', 'auto');
					if (tallestChildPannel <= $(this).height()) {
						//alert('works');
						tallestChildPannel = $(this).height();
						thisElement.children('.article_imagetextblock_pannel').css('height', tallestChildPannel + 'px');
					}
				});
			});

		}

		if ($(this).parent().parent().hasClass('carousel_style_3')) {
			//alert('yes');
			 $(this).find('.article_imagetextblock').each( function(i) {
				 $(this).removeClass('article_stack_style_0').removeClass('article_stack_style_1').removeClass('article_stack_style_2').removeClass('article_stack_style_3').removeClass('article_stack_style_4').removeClass('article_stack_style_5').removeClass('article_stack_style_6');
			 });
		}
		
		 $(this).find('div.imagetextblock').find('.article_imagetextblock').each( function(i) {
			 var thisTitle = $(this).children().children('h2').text();
			 if (tallestChild < $(this).outerHeight()) {
				 tallestChild = $(this).outerHeight();
			 }
			 $(this).css({'min-width' : 100 / countChildren + '%'});
			 
			 
			 if (lockOnResize < 1) {
			 
				if ($(this).closest('.div_carousel_container').find('li.li_carousel_' + i).length < 1) {
                     //alert($(this).closest('.div_carousel_container').attr('class'));
                    if($(this).attr('class')){
                        if($(this).attr('class').includes("article_whitecopy")){
                            $(this).closest('.div_carousel_container').find('ul.ul_carousel_nav').append('<li class="li_carousel_' + i + '"><a href="#" aria-label="'+thisTitle.trim()+'"><span class="whiteCopy_List" style="display: none">' + i + '</span>' + thisTitle + '</a></li>');
                        } else{
                            $(this).closest('.div_carousel_container').find('ul.ul_carousel_nav').append('<li class="li_carousel_' + i + '"><a href="#" aria-label="'+thisTitle.trim()+'"><span style="display: none">' + i + '</span>' + thisTitle + '</a></li>');
                        }
                    }
                }

                if($(this).closest('.div_carousel_container').attr('class').includes('carousel_style_1')){
                     if($(this).closest('.div_carousel_container').find('.article_imagetextblock').attr('class').includes('article_whitecopy')){
                        $(this).parent().parent().parent().next().children().css("filter","grayscale(1) invert(1)");
                        $(this).parent().parent().parent().next().next().children().css("filter","grayscale(1) invert(1)");
                     } else{
                        $(this).parent().parent().parent().next().children().css("filter","grayscale(1) invert(0)");
                        $(this).parent().parent().parent().next().next().children().css("filter","grayscale(1) invert(0)");
                     }
                 }
				
			 }
			 
			 
		 });
		//alert(countChildren);
		$(this).css({'width' : 100 * countChildren + '%'});
		$(this).parent().find('a.carousel_arrow').css({'top' : ((thisElement.outerHeight(true) / 2) - 34) + 'px'});
		$(this).parent().find('a.arrow_style1').css({'top' : '50%'});
		
		
	});
}

function headerCarousel(headerWidth) {
	//alert('active');
    $('div.parsysheadercarousel').each( function() {
        //alert('active');
        var thisElement = $(this)
        var countChildren = $(this).find('.article_imagetextblock').length;		
        var tallestChild = 0;

        if(countChildren > 0){
            $(this).parent().append('<ul class="ul_carousel_nav"></ul>');
        }

        //$(this).next().append('<a class="previous_arrow" href="#" style="position: absolute;"><img class="previous_arrow_image" src="img/carousel_left.png" width="25" height="25" alt="Move carousel left" style="position: absolute;left: -33px;-webkit-filter: grayscale(1) invert(1);filter: grayscale(1) invert(1);margin-bottom: -13px;"></a>');
        // Check that this parents parent has class of 'carousel_style_2' and if it does take off the 'article_imagetextblock' from all of the children articles so that we can restyle the articles and contain them in an outer container of 'article_imagetextblock' to avoid a big block of overiding css with to many '!important's and not altering the jquery that we have worked very hard on as it is so great and solid and perfect...
         $(this).find('.article_imagetextblock').each( function(i) {
             //$(this).css({'min-width' : 100 / countChildren + '%'});
             $(this).css('width', headerWidth + 'px');

             if ($(this).parent().parent().parent().parent().parent().find('li.li_carousel_' + i).length < 1) {
                    $(this).parent().parent().parent().parent().parent().find('ul.ul_carousel_nav').append('<li class="li_carousel_' + i + '"><a href="#" aria-label="Header Carousel List Icons"><span style="display: none">' + i + '</span></a></li>');
             }

         });
        //alert(countChildren);
        //$(this).css({'width' : 100 * countChildren + '%'});
        //$(this).next().append('<a class="next_arrow" href="#" style="position: absolute;"><img class="next_arrow_image" src="img//carousel_right.png" width="25" height="25" alt="Move carousel right" style="-webkit-filter: grayscale(1) invert(1);filter: grayscale(1) invert(1);position: absolute;left: 3px; "></a>');

    });
}

// Generic iframe resizer to compensate for iframes with responsive widths
function resizeIframe() {
	
	// Find iframes and proportion them to widescreen
	$('iframe').not('aside iframe, iframe.iframe_map').each( function() {
		if ($(this).parents().hasClass('div_pathmotion')) {
			//$(this).hide();
		} else {
			$(this).css({'height' : $(this).width() / 16 * 9 });
		}
	});
		
}

// Generic Skimmer to equalise heights of ragged content blocks
function equaliseHeights(thisElement) {

    // Set a seed value
	maxHeight = -1;
	// Set the heights of the affected objects to auto so they measure their content
	thisElement.css('height', 'auto');
	
	// Loop over the elements to hit them one by one
	thisElement.each(function(i) {
		// Update the max height var if the looped element is bigger than any of the previously found ones
		maxHeight = maxHeight > $(this).height() ? maxHeight : $(this).height();
	});
	
	// Reloop over everyting once we have the maxsize so they all match
	thisElement.each(function() {
		$(this).height(maxHeight);
	});

}

function backToTop() {
	$('body, html').animate({
		scrollTop: '0px'
	}, 2000);	
}


function openCloseTKOSP() {

	$('.form_search').slideUp();
    $('a#a_tkosp_button').blur();

    var nMaxHeight = $('section#section_tkosp').attr('data-maxheight');

    if ($('section#section_tkosp').css('top') == '-' + nMaxHeight + 'px') {
		$('section#section_tkosp').animate({'top': '0px'});
		$('#div_fixed_header').animate({'margin-top': nMaxHeight + 'px'});
		$('a#a_tkosp_button').animate({'background-position-y': '-28px'});
	} else {
		$('section#section_tkosp').animate({'top': '-' + nMaxHeight + 'px'});
		$('#div_fixed_header').animate({'margin-top': '0px'});
		$('a#a_tkosp_button').animate({'background-position-y': '5px'});
	}

};

function placeholderFormTextFOCUS(thisElement) {
    if (thisElement.val() == thisElement.attr('placeholder')) {
		thisElement.val('');
	}
}

function placeholderFormTextBLUR(thisElement) {
	if (thisElement.val() == '' || thisElement.val().trim().length == 0) {
		thisElement.val('');
	}else{
	    thisElement.val(thisElement.val().trim());
	}
}


function copyTags(thisElement) {
	// Remove them if they already exist
	thisElement.children('li.li_taglist_resource').remove();
	// Declare empty array to push the tag names onto
	var aAllTags = [];
	// Declare an array to hold the filtered/unique values
	var aUniqueTags = [];
	// Loop over the resource tag list
	$('li.li_taglist_resource a.a_tagtitle').each( function() {
		// Clone and append the tags into the header tag list
		// if ($.inArray($(this).text(), aUniqueTags) === -1) {
		if ($.inArray($(this).text(), $.map(aUniqueTags, function(v) { return v[0]; })) === -1) {
			aUniqueTags.push([$(this).text(), $(this).next().text()]);
		}
	});
	
	aUniqueTags.sort(sortTags);
	
	for (var i = 0; i < aUniqueTags.length; i++) {
		$('<li class="li_taglist_resource" data-tagid="' + aUniqueTags[i][1] + '"><a href="#">' + aUniqueTags[i][0] + '</a></li>').appendTo(thisElement);	
	}
	
	// Hide the filter menu if there are no tags
	if (aUniqueTags.length == 0) {
		//thisElement.prev().remove();
		thisElement.remove();
	}

}

function reorderBlogArticles(thisElement) {

    thisElement.children('li').each( function() {
        if (typeof $(this).attr('data-dateorder') !== typeof undefined && $(this).attr('data-dateorder') !== false) {
            var d = Date.parse($(this).attr('data-dateorder').replace('BST', 'GMT'));
            $(this).attr('data-dateparse', d.toString());
        }
    });

    var thisList = thisElement.children('li');
    thisList.sort(function(a, b){
        return $(b).data('dateparse')-$(a).data('dateparse')
    });
    thisElement.html(thisList);

}

function sortTags(a, b) {
    if (a[0] === b[0]) {
        return 0;
    } else {
        return (a[0] < b[0]) ? -1 : 1;
    }
}

// Function to take account of selected filtration tags, highlight them and filter the resources accordingly
	function filterResources(thisElement) {
		//alert('working');
		// Mark the tag as selected (if unselected) or unselected (if already selecetd)
		thisElement.toggleClass('a_selected');
		// Reset each element in the resource list before re-looping
		$('ul.ul_latest_briefings li').removeClass('a_nomatch');
		// Loop over the selected tags
		$(thisElement.parent().parent().find('a.a_selected')).each( function() {
			//alert($(this).parent().data('tagid'));
			//U$(this).css('background-color', '#FF0000');
			var thisElementOuter = $(this).parent();
			$('ul.ul_latest_briefings li').not('.a_nomatch').each( function() {
				//alert('looping: ' +  $(this).parent().data('tagid') + ' : ' + thisElementOuter.data('tagid') );
				if ($(this).html().indexOf(thisElementOuter.data('tagid')) == -1) {
					//alert("Not Found");
					$(this).slideUp();
					$(this).addClass('a_nomatch');
					//return true;
				} else {
					//alert("Found");
					$(this).slideDown();
				}
			});	
			
		});
		// If no tags are selected we have to manually re-show all reasources
		if ($(thisElement.parent().parent().find('a.a_selected')).length == 0) {
			//thisElement.parent().next().children('li').slideDown();
			$('ul.ul_latest_briefings li').slideDown();
		}
	}

// Functions to control image-based carousels
function imageTextBlockShowDetail(thisElement) {
    thisElement.fadeOut();
	thisElement.prev().slideDown();
    thisElement.prev().before('<div class="div_black_grad"></div>');
    thisElement.parent().find('div.div_black_grad').fadeIn();
}

function imageTextBlockHideDetail(thisElement) {
	thisElement.parent().slideUp();
	thisElement.parent().next().slideDown();
    thisElement.parent().parent().find('div.div_black_grad').fadeOut(500, function() {
		$(this).remove();
    });
}

function openImage(s) {
	$('body').append('<div id="div_openimage"><a href="#" id="a_closeimage">X</a><img id="img_openimage" src="' + s + '" /></div>');
    var imageHeight = 0;
    var imageWidth = 0;
    var orientation = "portrait";
	$('img#img_openimage').on("load",function() {
		$(this).parent().fadeIn();
        imageHeight = $(this).height();
		imageWidth = $(this).width();
        if (imageWidth > imageHeight) {
			orientation = 'landscape';
        }
		$(this).addClass('img_' + orientation);
        if (orientation == 'landscape') {
			$(this).css('margin-top', '-' + ($('img#img_openimage').height() / 2) + 'px');
        }
        if ($('img#img_openimage').width() > $(window).width()) {
            $(this).css({'width': '90%', 'height': 'auto', 'top': '50%'});
            $(this).css({'margin-top': '-' + ($('img#img_openimage').height() / 2) + 'px'});
        }
        if ($('img#img_openimage').height() > $(window).height()) {
        	$(this).css({'height': '90%', 'width': 'auto', 'top': '50%'});
       		$(this).css({'margin-top': '-' + ($('img#img_openimage').height() / 2) + 'px'});
        }
	});
}

function getGeoLocation() {

    // If an iframe is present we trigger the geo-location
	if ($('iframe').length > 0) {
        if (window.location.hash.indexOf('geo') == -1) {
            $.ajax({
                url: 'https://api.ipstack.com/check?access_key=aaa626cb605e60c73e3fc45dbf32361d'
            }).done(function(data) {
                var aCountryCode = data.country_code;
                geoControlVideo(aCountryCode);
            });
        } else if (window.location.hash.indexOf('geo') > -1) {
            var sGeoOverride = window.location.hash.substring(5);
            $('body').attr('data-geolocation', sGeoOverride);
            geoControlVideo(sGeoOverride);
            alert('Simulating location: ' + sGeoOverride);
        }
    }
}

function geoControlVideo(s) {
    $('iframe').each( function() {
        if (typeof $(this).closest('article.article_imagetextblock').attr('data-block') !== 'undefined') {
            var sCountryToMatch = $(this).closest('article.article_imagetextblock').attr('data-block');

            if (sCountryToMatch.indexOf(s) == -1) {
                // This content isn't blocked so render the iframe
                if (typeof $(this).attr('data-src') !== 'undefined') {
                    $(this).attr('src',  $(this).attr('data-src'));
                }
            } else {

				// This content IS BLOCKED so DON'T render the iframe
				if (typeof $(this).closest('article.article_imagetextblock').find('h2').attr('data-block') !== 'undefined') {
                    $(this).closest('article.article_imagetextblock').find('h2').text($(this).closest('article.article_imagetextblock').find('h2').attr('data-block'));
                }
                if (typeof $(this).closest('article.article_imagetextblock').find('span').attr('data-block') !== 'undefined') {
                    $(this).closest('article.article_imagetextblock').find('span').html($(this).closest('article.article_imagetextblock').find('span').attr('data-block'));
                }
                if (typeof $(this).closest('article.article_imagetextblock').find('a.a_standardlink').attr('data-blocklinktext') !== 'undefined') {
                    $(this).closest('article.article_imagetextblock').find('a.a_standardlink span').text($(this).closest('article.article_imagetextblock').find('a.a_standardlink').attr('data-blocklinktext'));
                    $(this).closest('article.article_imagetextblock').find('a.a_standardlink').attr('title', $(this).closest('article.article_imagetextblock').find('a.a_standardlink').attr('data-blocklinktext'));
                }
                if (typeof $(this).closest('article.article_imagetextblock').find('a.a_standardlink').attr('data-blocklink') !== 'undefined') {
                    $(this).closest('article.article_imagetextblock').find('a.a_standardlink').attr('href', $(this).closest('article.article_imagetextblock').find('a.a_standardlink').attr('data-blocklink'));
                }
                if (typeof $(this).attr('data-blockimage') !== 'undefined') {
                    $(this).parent().append('<div class="div_imagetextblock_imagecropper"><img class="img_imagetextblock" src="' + $(this).attr('data-blockimage') + '" width="" height="" alt="" /></div>');
                }
                $(this).remove();
            }
        } else if ($(this).hasClass('cc-yt-player')) {
			// This iframe is not in an imagetextblock
			if (typeof $(this).attr('data-block') !== 'undefined') {
				var sCountryToMatch = $(this).attr('data-block');

                if (sCountryToMatch.indexOf(s) == -1) {
                    // This content isn't blocked so render the iframe
                    if (typeof $(this).attr('data-src') !== 'undefined') {
                        $(this).attr('src', $(this).attr('data-src'));
                    }
                } else {
					$(this).remove();
                }
            }
        }
    });
}

function getRelatedContent(thisElement) {

	if (thisElement.hasClass('selected')) {
        thisElement.removeClass('selected');
        thisElement.parent().next().slideUp();
    } else {
        $('div.div_related_list').slideUp();
        $('section.section_related_content h2 a').removeClass('selected');
        thisElement.addClass('selected');
		if (thisElement.parent().next().children().length == 0) {
            thisElement.parent().next().load(thisElement.closest('section').attr('data-search'), function() {
                thisElement.parent().next().slideDown();
            });
        } else {
            thisElement.parent().next().slideDown();
        }
    }



}