// Global vars
var cc_cpuser_from_cookie;
var cc_cpuser_guid;
var cc_cpuser_userid;
var cc_cpuser_authstatus;
var cc_cpuser_organizationid;
var cc_cpuser_usertype;
var cc_cpuser_bookmarks;
var cc_aa_js_pagename;
var bTransitionLock = false;
var bAnimationLockCP = false;
var cc_content_path = '';
var selectedTab1=0;
var selectedTab2=0;
var selectedTab3=0;
var selectedTab4=0;
var selectedTab5=0;
var maxHeight=-1;
//var cc_cc_iaid = cc_cc_iaid;

$(document).ready(function () {

    //JS to add Filters button on search results page - START
    if(window.location.pathname.includes("/search.html")){
        const button = document.createElement('button')
        button.innerText = 'Filters'
        button.id = 'FilterButton'
        document.getElementById("main_content").appendChild(button)
        $("#FilterButton").css({
            "display": "none",
            "position": "fixed",
            "bottom": "50px",
            "left": "80px",
            "z-index": "99999",
            "font-size": "18px",
            "background-color": "#45A5DA",
            "border":"none",
            "color": "white",
            "cursor": "pointer",
            "padding": "15px",
            "border-radius": "4px"
        })
        button.addEventListener("click", myFunction)
        function myFunction(){
            document.body.scrollTop = 450;
            document.documentElement.scrollTop = 450;
        }
        window.onscroll = function() {scrollFunction()};

        function scrollFunction() {
            if ($(window).width() > 900) {
                if (document.body.scrollTop > 1000 || document.documentElement.scrollTop > 1000) {
                    button.style.display = "block";
                } else {
                    button.style.display = "none";
                }
            }
            else {
                button.style.display = "none";
            }
        }

        window.onresize = function() {displayFilteronResize()};

        function displayFilteronResize() {
            if ($(window).width() > 900) {
                if (document.body.scrollTop > 1000 || document.documentElement.scrollTop > 1000) {
                    button.style.display = "block";
                }
            } else {
                button.style.display = "none";
            }
        }
    }
    //JS to add Filters button on search results page - END

	var asd = $("#Toolkit").attr("href");
	var exter = "financialmarkets";
	if(asd !== undefined){
		if(asd.indexOf(exter) != -1){
		 $('#Toolkit').attr('target', '_blank');
		}
	}

	var cceurl = $("#Toolkits").attr("href");
	var ccexter = "financialmarkets";
	if(cceurl !== undefined){
		if(cceurl.indexOf(ccexter) != -1){
		 $('#Toolkits').attr('target', '_blank');
		}
	}


	var setrnl = $('ul.ul_layout_fullbleed li a.smart').attr("href");
	if(setrnl !== undefined){
		 if(setrnl.indexOf(exter) != -1){
		 $('ul.ul_layout_fullbleed li:nth-child(1) a.smart').attr('target', '_blank');
		}
	}
	
	


    // ================== CHECK IF WE NEED TO REDIRECT TO PRE-LOGIN LOCATION ================== //
	//window.location.href.indexOf('ciftci') > -1
    // executeSamlRedirect(); // Called every time but only executes if we have a cc_saml_redirect cookie present

    // ============================ START: GLOBAL JS CONSTRUCTUION ============================ //
	//console.log(cc_cc_iaid);
    cc_aa_js_pagename = $('title').text().replace('|', '').replace('\'', '').replace('  ', ' ');
    if(window.location.href.indexOf('cavenagh') > -1){

		cc_content_path = '/content/cavenagh-law';
		$('h4.h4_more_filters').hide();
		$('h2#h2_tkosp_button').hide();
	}else if(window.location.href.indexOf('ycap') > -1){

		cc_content_path = '/content/site-ycap';
		$('h4.h4_more_filters').hide();
		$('h2#h2_tkosp_button').hide();
	}else if(window.location.href.indexOf('ciftci') > -1){

		cc_content_path = '/content/site-ycap';
		$('h4.h4_more_filters').hide();
		$('h2#h2_tkosp_button').hide();
	}
	else{
		cc_content_path = '/content/cliffordchance';
	}
	console.log('CONTENT PATH: ' + cc_content_path);

    // ========================== START: GLOBAL COOKIE SERVICE CALLS ========================== //
	callsiteimprove();
    callCookieSetter(); // Function is called every time but only executes on Okta referral
    callCustomAuthHandler(false); // Function is called every time but only executes when we have an Okta user cookie

    // getIAContact(); // Temporary call for testing

    // ========================== START: INITIALISATION ========================== //

    // Set initial visibility of log-in dependent links
    evalLogin(true);

	//On load
   var visibleAnchor= $('ul.ul_multilistcontainer_manual_tabs').find('li:visible:first').children('a');
   var tagvisibleAnchor= $('ul.ul_tagmultilistcontainer_tabs').find('li:visible:first').children('a');

   // positionTabArrow($('#a_multilist_manual_tab1'));
    //loadArticleFeedsMulti($('#a_multilist_manual_tab1'));
    //resetShowMoreMulti($('#a_multilist_manual_tab1'));

    positionTabArrow(visibleAnchor);
    loadArticleFeedsMulti(visibleAnchor);
    resetShowMoreMulti(visibleAnchor);
    
    positionTabArrow(tagvisibleAnchor);
    loadTagArticleFeeds(tagvisibleAnchor);
    resetShowMoreMulti(tagvisibleAnchor);

    // ================================ START: CLICK FUNCTIONS ================================ //

    $('section#section_tkosp').on('click', 'a.a_createtestcookie', function (e) {
        createTestCookie($(this).data('uid'));
        e.preventDefault();
    });

    $('.ul_multilistcontainer_tabs').on('click', 'li a', function (e) {
        if (!bTransitionLock) {
            bTransitionLock = true;
            $(this).parent().parent().children('li').children('a').removeClass('selected');
            $(this).addClass('selected');
            loadArticleFeeds($(this));
            positionTabArrow($(this));
            resetShowMore($(this));
        }
        e.preventDefault();
    });
    
    $('.ul_tagmultilistcontainer_tabs').on('click', 'li a', function (e) {
        if (!bTransitionLock) {
            bTransitionLock = true;
            $(this).parent().parent().children('li').children('a').removeClass('selected');
            $(this).addClass('selected');
            loadTagArticleFeeds($(this));
            positionTabArrow($(this));
            resetShowMore($(this));
        }
        e.preventDefault();
    });

	//Start : Multi field Manual list


    $('.ul_multilistcontainer_manual_tabs').on('click', 'li a', function (e) {

        if (!bTransitionLock) {
            bTransitionLock = true;
            $(this).parent().parent().children('li').children('a').removeClass('selected');
            $(this).addClass('selected');
			if($(this).parent().data('showfilter') == 'None')
			{
				 $('form#ifElementExist').remove();
                 $('form#ifElementExist').hide();
			}
           loadArticleFeedsMulti($(this));
            positionTabArrow($(this));
            resetShowMoreMulti($(this));
        }
        e.preventDefault();
    });

    $('.section_multilistcontainer').on('click', 'a.a_showmore', function (e) {
        if ($(this).data('state') == 'expand') {
            //alert('condition works');
            e.preventDefault();
            expandArticlesCP($(this));
            if ($(this).attr('href') === undefined) {
                $(this).slideUp();
            }
        } else {
            window.location.href = $(this).attr('href');
        }

    });

    $('.search2019results, .div_multilistcontainer_target, .ul_imagetextblockv3_cp, .div_multilistcontainer_adobetarget, .div_alertersharebar, .p_cbg_utils').on('click', 'a.a_bookmark_cp', function (e) {
        addBookmark($(this));
        if ($(this).parent().parent().find('div.div_bookmark_popup').length > 0) {
            $(this).parent().parent().find('div.div_bookmark_popup').slideDown().children('strong').addClass('strongalert');
        }
        e.preventDefault();
    });

    $('.div_multilistcontainer_target, .ul_imagetextblockv3_cp').on('click', 'a.a_remove_bookmark_cp', function (e) {
        e.preventDefault();
        removeBookmark($(this));
        e.preventDefault();
    });

    $('.section_multilistcontainer').on('click', 'a.a_carousel_next_cp', function (e) {
        animateImageTextBlockV3($(this), 'next');
        e.preventDefault();
    });

    $('.section_multilistcontainer').on('click', 'a.a_carousel_prev_cp', function (e) {
        animateImageTextBlockV3($(this), 'prev');
        e.preventDefault();
    });

    $('.section_multilistcontainer').on('change', 'select.select_multilist_filter_jurisdiction', function (e) {
        filterMultiListJurisdiction($(this));
        e.preventDefault();
    });

    $('form.form_expose_abstract').on('change', 'input.input_checkbox', function (e) {
        expandAlertersCP($(this));
        e.preventDefault();
    });

    $('.section_multilistcontainer').on('click', 'ul.ul_imagetextblockv3_cp_dots li a', function (e) {
        animateImageTextBlockV3FromDots($(this));
        e.preventDefault();
    });

    $('section#section_cp_marquee_info').on('click', 'a.a_marquee_login', function (e) {
        $('a#a_tkosp_button').trigger('click');
        $('a#a_tkosp_button').trigger('focus');
        let backtologin = document.getElementsByClassName('auth-footer');
        if (backtologin.length > 0) {
            backtologin = backtologin[0].getElementsByTagName('a');
            if (backtologin.length > 0) {
                backtologin[0].click();
            }
        }
        e.preventDefault();
    });

    $('section#section_cp_messagecentre').on('click', 'a.a_messagecentre_close', function (e) {
        closeMessageCentre($(this));
        e.preventDefault();
    });

    $('article.article_listregulators').on('click', 'a.a_loadregulators', function (e) {
        // Split this up so it can execute on load to pre-remove the countries that have no matching regulators...
        loadRegulators($(this));
        e.preventDefault();
    });

    $('nav#nav_atoz').on('click', 'ul li a', function (e) {
        $('nav#nav_atoz ul li a').removeClass('selected');
        $(this).addClass('selected');
        filterCountriesByLetter($(this));
        e.preventDefault();
    });

    $('form#form_regulator_search').on('keyup', 'input', function (e) {
        filterCountriesByTextInput($(this));
        e.preventDefault();
    });

    $('section.section_searchpanel').on('click', 'a.a_moreresults', function (e) {
        loadSearchAJAX($(this).parent().find('div.div_searchresultstarget'), getFilters(), true, false, false, false);
        e.preventDefault();
    });

    $('section.section_searchpanel').on('click', 'a.a_moretags', function (e) {
        // Do less
        e.preventDefault();
    });

    $('section.section_searchfilterspanel').on('click', 'li.li_search_tagfilter_selected a, a.a_search_tagfilter', function (e) {
        var thisElement = $(this);
        $(this).parent().parent('ul').slideUp(function () {
            filterResults(thisElement);
            scrollToSearch();
            // $('html, body').stop().animate({ scrollTop: '550px'});
        });
        e.preventDefault();
    });

    $('section.section_searchfilterspanel').on('click', 'a.a_search_tagfilter_warn', function (e) {
        filterResultsWarning($(this));
        e.preventDefault();
    });

    $('section.section_searchfilterspanel').on('click', 'div.div_filter_warning a', function (e) {
        var thisElement = $(this).parent().parent().prev();
        thisElement.parent().parent('ul').slideUp(function () {
            filterResults(thisElement);
            scrollToSearch();
        });
        e.preventDefault();
    });

    $('form.form_filter_search').on('keyup', 'input', function (e) {
        console.log('Registered key');
        // predictSearch($(this));
        e.preventDefault();
    });

    $('div.div_dropdown_find_lawyer').on('submit', 'form', function (e) {
        transferSearch($(this));
        e.preventDefault();
    });

    $('div.div_dropdown_find_lawyer form').on('keyup', 'input', function (e) {
        predictSearch($(this));
        e.preventDefault();
    });

    $('body').on('mouseenter', 'div#div_search_predictions ul li a', function (e) {
        $('div#div_search_predictions ul li a').removeClass('selected');
        $(this).addClass('selected');
        e.preventDefault();
    })

    $('section#section_searchfilters_2019 section.section_searchfilterspanel').on('click', 'h4 a', function (e) {
        if ($(this).parent().hasClass('h4_more_filters')) {
            showSearchFilters($(this));
        } else {
            $('section#section_searchfilters_2019 section.section_searchfilterspanel ul').not($(this).parent().next('ul')).not('ul.ul_dates').slideUp().prev().children().removeClass('selected');
            if ($(this).hasClass('selected')) {
                $(this).removeClass('selected');
                $(this).parent().next('ul').not('ul.ul_dates').slideUp();
            } else {
                $(this).addClass('selected');
                $(this).parent().next('ul').slideToggle();
                $(this).parent().next('ul').children('li').each(function () {
                    if ($(this).text() == $(this).prev().text()) {
                        $(this).remove();
                    }
                });
            }
        }

        e.preventDefault();
    });

    $('form.form_relevance_alpha').on('change', 'input.input_checkbox', function (e) {
        switchSortOrder($(this));
        e.preventDefault();
    });

    $('section#section_searchresults_2019 h3').click(function () {
        // alert('clicked');
        $('section#section_searchfilters_2019').parent().slideDown();
        $('section#section_searchfilters_2019 h3').slideDown();
        return false;
    });

    $('section#section_searchfilters_2019').on('click', 'h3', function (e) {
        $('section#section_searchfilters_2019').parent().slideUp();
        e.preventDefault();
    });

    $('section.section_search').on('change', 'select', function (e) {
        quickFilter($(this));
    });

    $('a.a_help').each(function (i) {

        $(this).on('click', function (e) {
            //alert($(this).attr('title'));
            //$(this).animate({'width' : '50%'});
            var thisWidth = $(this).css('width');
            //alert(thisWidth);
            if ($(this).hasClass('selected')) {
                $(this).removeClass('selected');
                $(this).animate({ 'color': '#ffffff' }, function () {
                    var currentWidth = thisWidth;
                    $(this).css({ 'width': 'auto' });
                    $(this).text('?');
                    thisWidth = $(this).width();
                    $(this).css({ 'width': currentWidth });
                    $(this).animate({ 'width': thisWidth, 'padding': '6px', 'padding-top': '0px', 'padding-bottom': '0px', 'border-bottom-right-radius': '20px' });
                    $(this).animate({ 'color': '#000000' });
                });
            } else {
                $(this).addClass('selected');
                $(this).animate({ 'color': '#ffffff' }, function () {
                    var currentWidth = thisWidth;
                    $(this).css({ 'width': 'auto' });
                    $(this).text($(this).attr('title'));
                    thisWidth = $(this).width() + 10;
                    $(this).css({ 'width': currentWidth });
                    $(this).animate({ 'width': thisWidth, 'padding': '8px', 'border-bottom-right-radius': '0px' });
                    $(this).animate({ 'color': '#000000' });
                });
            }
            return false;
        });
    });

    $('div.div_cp_message_wrapper').on('click', 'a.a_messagecentre_link', function (e) {
        if ($(this).attr('href').indexOf('login=true') > -1) {
            openCloseTKOSP();
            return e.preventDefault();
        }
    });

    $('div.div_searchresultstarget').on('click', 'ul.ul_searchlist > li > a', function (e) {
        /*
        if (!!$.cookie('oktauser') && ($(this).attr('href').indexOf('/alerters/') > -1 || $(this).attr('href').indexOf('/current-awareness/') > -1)) {
            showQuickView($(this));
            e.preventDefault();
        }
        */


		if($("#aaa").text() == 'OpenAccess' && ($(this).attr('href').indexOf('/cbg/') > -1)) {
			showQuickViewInline($(this));
            e.preventDefault();
		} else {
			if ((!!$.cookie('oktauser') && ($(this).attr('href').indexOf('/cbg/') > -1)) || (!!$.cookie('oktauser') && ($(this).attr('href').indexOf('/alerters/') > -1))) {
            showQuickViewInline($(this));
            e.preventDefault();
			}
		}

    });

    $('body').on('click', 'div#div_serachresultblur', function (e) {
        hideQuickView($(this));
        e.preventDefault();
    });

    $('body').on('click', 'nav#nav_iframecontrols a.a_qv_prevnext', function (e) {
        showQuickView($(this));
        e.preventDefault();
    });

    $('body').on('click', 'nav#nav_iframecontrols a.a_qv_close', function (e) {
        $('div#div_serachresultblur', window.parent.document).trigger('click');
        e.preventDefault();
    });


    // ========================= START: PROFILE SPECIFIC FUNCTIONS ========================== //

    // if ($('div#div_profile_publications').length > 0) {
    $('a.section_publicationsandinsights').parent().parent().hide();
    $('a.section_publicationsandinsights').parent().hide();
    $('a.section_relevantexperince').parent().hide();

    $('div#div_profile_news').load(cc_content_path + '/search-2019/search-2019-results.html?query=' + $('section#section_publicationsandinsights').data('thispath') + '&path=/content/cliffordchance/news/news&page=1&pageitems=5&date=5y&facets=false&options=none&_charset_=UTF-8&c=1&sort=Date&exact=true', function () {

        if ($('section.section_relevantexperince div section').length == 0 && $('div#div_profile_news').children().length == 0) {
            $('section.section_relevantexperince').hide();
            $('a.section_publicationsandinsights').trigger('click');
        } else {
            $('a.section_publicationsandinsights').parent().parent().show();
            $('a.section_relevantexperince').parent().fadeIn();
        }
        if ($('div#div_profile_news ul.ul_searchlist').length == 0) {
            $('h3#h3_headernews').hide();
        }
        if ($('div#div_profile_news ul').children().length < 5) {
            $('a#a_morenews').hide();
        }

        $('div#div_profile_publications').load(cc_content_path + '/search-2019/search-2019-results.html?query=' + $('section#section_publicationsandinsights').data('thispath') + '&path=/content/cliffordchance/briefings&page=1&pageitems=5&date=5y&facets=false&options=none&_charset_=UTF-8&c=1&sort=Date&exact=true', function () {

            $('div#div_profile_podcasts').load(cc_content_path + '/search-2019/search-2019-results.html?query=' + $('section#section_publicationsandinsights').data('thispath') + '&path=/content/cliffordchance/insights/resources/podcast-library&page=1&pageitems=5&facets=false&options=none&_charset_=UTF-8&c=1&sort=Date&exact=true', function () {

                if ($('div#div_profile_blogs').length > 0) {

                    $('div#div_profile_blogs').load(cc_content_path + '/search-2019/search-2019-results.html?query=' + $('section#section_publicationsandinsights').data('thispath') + '&path=/content/cliffordchance/insights/resources/blogs&page=1&pageitems=5&facets=false&options=none&_charset_=UTF-8&c=1&sort=Date&exact=true', function () {

                        if ($('section.section_publicationsandinsights div section').length == 0 && $('div#div_profile_publications').children().length == 0 && $('div#div_profile_blogs ul.ul_searchlist').length == 0 && $('div#div_profile_podcasts ul.ul_searchlist').length == 0) {
                            $('section.section_publicationsandinsights').hide();
                            if ($('section.section_relevantexperince').is(":hidden")) {
                                $('ul.ul_article_greytabs_generic').hide();
                            }
                        } else {
                            $('a.section_publicationsandinsights').parent().parent().show();
                            $('a.section_publicationsandinsights').parent().fadeIn();
                        }
                        if ($('div#div_profile_publications ul').children().length == 0) {
                            $('h3#h3_headerpubs').hide();
                        }
                        if ($('div#div_profile_blogs ul.ul_searchlist').length == 0) {
                            $('h3#h3_headerblogs').hide();
                        }
                        if ($('div#div_profile_podcasts ul.ul_searchlist').length == 0) {
                            $('h3#h3_headerpodcasts').hide();
                        }
                        if ($('div#div_profile_publications ul').children().length < 5) {
                            $('a#a_morepubs').hide();
                        }
                        if ($('div#div_profile_blogs ul.ul_searchlist').children().length < 5) {
                            $('a#a_moreblogs').hide();
                        }
                        if ($('div#div_profile_podcasts ul.ul_searchlist').children().length < 5) {
                            $('a#a_morepodcasts').hide();
                        }

                    });

                }

            });

            /*
            if ($('section.section_publicationsandinsights div section').length == 0 && $('div#div_profile_publications').children().length == 0) {
                $('a.section_publicationsandinsights').hide();
                //alert('hide');
            } else {
                $('a.section_publicationsandinsights').fadeIn();
                //alert('show');
            }
            */
        });

    });
    // }

    /*
    if ($('div#div_profile_podcasts').length > 0) {
        $('a.section_blogsandpodcasts').hide();
        $('div#div_profile_podcasts').load(cc_content_path + '/search-2019/search-2019-results.html?query=' + encodeURI($('title').text()) + '&path=/content/cliffordchance/resources/podcast-library&page=1&pageitems=5&facets=false&options=none&_charset_=UTF-8&c=1&sort=Date', function() {
            if ($('div#div_profile_blogs').length > 0) {
                $('div#div_profile_blogs').load(cc_content_path + '/search-2019/search-2019-results.html?query=' + encodeURI($('title').text()) + '&path=/content/cliffordchance/hubs&page=1&pageitems=5&facets=false&options=none&_charset_=UTF-8&c=1&sort=Date', function() {
                    if ($('div#div_profile_blogs ul.ul_searchlist').length == 0 && $('div#div_profile_podcasts ul.ul_searchlist').length == 0) {
                        $('a.section_blogsandpodcasts').hide();
                        //alert('hide');
                    } else {
                        $('a.section_blogsandpodcasts').fadeIn();
                        //alert('show');
                    }
                });
            }
        });
    }
    */

    // ========================== START: REGULATORS CONTROL ========================== //

    if ($('article.article_listregulators').length > 0) {
        console.log('FOUND article_listregulators');
        $('ul#ul_regulator_countries > li').each(function () {
            console.log('FOUND ul_regulator_countries li');
            removeNonMatchingProducts($(this));
        });
    }

    // ========================== START: POST CLICK INITIALISATION ========================== //

    evalLoginTriggers();
    loadSearches('None', true, true);
    truncateMenu($('select.tags_sector'));

});

$(window).on("load",function () {

    var aQueryString = getParams(window.location.href);

    // Look for query to trigger log-in tab
    if (aQueryString['login'] == 'true') {
        $('h2#h2_tkosp_button a').trigger('click');
        $('h2#h2_tkosp_button a').trigger('focus');
    }

    // Look for query to scroll to bookmarks
    if (aQueryString['bookmarks'] == 'true' && $('section#bookmarks').length > 0) {
        $('html, body').animate({ 'scrollTop': ($('section#bookmarks').offset().top - 140) + 'px' }, 1000);
    }

    // Fix panel widths to make them distribute evenly
    redistributePanels();

    // Look for an image text block and initialise it if there is one
    if ($('ul.ul_imagetextblockv3_cp').length > 0) {
        initialiseImageTextBlockV3();
    }

    $('nav#nav_atoz ul li a').each(function () {
        fadeFilterCountriesByLetter($(this));
    });

    // console.log('First Li element: ' + $('.ul_multilistcontainer_tabs li:visible:first a').text());

    $('ul.ul_imagetextblockv3_cp_dots li.dot_0 a').addClass('selected');

    // scrollToSearch();
    moveSearchToTop();

});

var windowWidth = $(window).width();
$(window).resize(function () {
    if ($(this).width() != windowWidth) {
        $('.ul_multilistcontainer_tabs').each(function () {
            positionTabArrow($(this).find('li a.selected'));
        });
        redistributePanels();
        initialiseImageTextBlockV3();
        $('ul.ul_imagetextblockv3_cp_dots li.dot_0 a').trigger('click');
    }

    fixFiltrationMenu();
});


$(window).keydown(function (e) {
    // Check if we have a predictive search available on the page and use key-presses to navigate
    if ($('div#div_search_predictions:visible').length > 0) {
        if (e.which === 40) {
            traversePredictiveSearch('Down');
            e.preventDefault();
        } else if (e.which === 38) {
            traversePredictiveSearch('Up');
            e.preventDefault();
        } else if (e.which === 13) {
            if ($('div#div_search_predictions:visible').find('a.selected').length > 0) {
                var href = $('div#div_search_predictions:visible').find('a.selected').attr('href');
                window.location.href = href;
                e.preventDefault();
            }
        }
    }

    if ($('div#div_search_predictions_nav:visible').length > 0) {
        if (e.which === 40) {
            traversePredictiveSearch('Down');
            e.preventDefault();
        } else if (e.which === 38) {
            traversePredictiveSearch('Up');
            e.preventDefault();
        } else if (e.which === 13) {
            if ($('div#div_search_predictions_nav:visible').find('a.selected').length > 0) {
                var href = $('div#div_search_predictions_nav:visible').find('a.selected').attr('href');
                window.location.href = href;
                e.preventDefault();
            }
        }
    }
});

$(window).scroll(function () {
    fixFiltrationMenu();
});

// ==================================== START: Universal functions =================================== //

function loadingIcon(bOpen, eTarget, sDetailH2, sDetailH3) {

    console.log('LOADING ICON | ' + bOpen + ' | ' + eTarget.attr('id') + ' | ' + sDetailH2 + ' | ' + sDetailH3);

    if (bOpen) {
        eTarget.append('<div class="div_loading" style="display: none;"><h2 style="text-align: center !important;">' + sDetailH2 + '</h2><h3>' + sDetailH3 + '</h3></div>');
        eTarget.children('div.div_loading').fadeIn('fast');
    } else {
        eTarget.children('div.div_loading').remove();
    }

}

// ================================== START: Cookie Service Functions ================================= //

function callCookieSetter() {

    console.log('Called callCookieSetter');
    console.log('document.referrer: ' + document.referrer);

    if (document.referrer.indexOf('cliffordchance.okta-emea.com') > -1 || document.referrer.indexOf('cliffordchance-dev.oktapreview.com') > -1) {

        // We are logging in soo we must ensure the cookieChecked cookie is cleared otherwise we won;t properly call the custom auth handler on callback
        document.cookie = "cc_checkedCookie" + "=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;";

        console.log('Found cliffordchance.okta-emea.com');
        loadingIcon(true, $('body'), 'One moment please', 'We are creating your account. Please stay on this page. <br /><strong>Do not refresh the page or use your browser\'s back button.</strong>');

        if (typeof $.cookie('oktauser') === 'undefined') {

            console.log('Cookie not present');

            $.ajax({
                url: '/cc/Cookie',
                type: 'POST',
                data: {},
                success: function (res) {
                    copyPrefsFromCookie();
                    copyBoomarksFromCookie();
                    evalMessageCentre();
                    internalExternal(); // Added this to try and solve the CR16 issue (still needs work)
                    evalLogin(true);
                    callCustomAuthHandler(true);
                    console.log('CALLBACK callCookieSetter');
                    loadingIcon(false, $('body'), '', ''); // Should we only set the loading icon to false after the callCustomAuthHandler is fiinished because it sets the IA Flag and the user might navigate away before it executes?
                    evalGMAT();
                    executeSamlRedirect(); // I think this might be causing IA Flags to net get set - it would be better in callCustomAuthHandler (possibly)
                },
                error: function (err) {
                    console.log(err);
                    loadingIcon(true, $('body'), 'Sorry', 'We are unable to create your account at the moment. <br />Please try again later.');
                }
            });

        } else {
            loadingIcon(false, $('body'), '', '');
        }
    }
}

function callCustomAuthHandler(bAvoidDuplicateCalls) {

    console.log('Called callCustomAuthHandler');

    // Check oktauser cookie exists and that the check cookie cookie has expired...
    if (!!$.cookie('oktauser')) {
    	//////////Change for US57494 ////////////////
    	if(window.location.href.match('alerter-finance.html') || window.location.href.match('alerter-c-m.html'))
		{
            $('.wysiwygbox').eq(1).hide();
            $('.aside_2col_container .parsyscol2 .imageAndTextLink').first().hide();
            $('.aside_2col_container .parsyscol2').children('.imageAndTextLink').eq(2).hide();
        }
        if(window.location.href.match('alerter-energy.html')){
            $('.wysiwygbox').eq(1).hide();
        }
    	//////////end Change for US57494 /////////////////

        if (!!$.cookie('cc_checkedCookie')) {

            if (!bAvoidDuplicateCalls) {
                copyPrefsFromCookie();
                copyBoomarksFromCookie();
                evalMessageCentre();
                internalExternal();
                evalGMAT();
                executeSamlRedirect(); // Added 19/12/2019 to counter internal redirects not cutting in
            }

        } else {

            $.ajax({
                url: '/cc/checkCookie',
                type: 'POST',
                data: {},
                success: function (res) {

                    if (!bAvoidDuplicateCalls) {
                        copyPrefsFromCookie();
                        copyBoomarksFromCookie();
                        evalMessageCentre();
                        internalExternal();
                        evalGMAT();
                        executeSamlRedirect(); // Added 19/12/2019 to counter internal redirects not cutting in
                    }

                    /*
                    // Possible tweak to this structure
                    if (bAvoidDuplicateCalls) {
                        loadingIcon(false, $('body'), '', '');
                        executeSamlRedirect();
                    } else {
                        copyPrefsFromCookie();
                        copyBoomarksFromCookie();
                        evalMessageCentre();
                        internalExternal();
                        evalGMAT();
                    }
                    */

                    $.cookie('cc_checkedCookie', 'true', { expires: 0.167, path: '/', secure: true });

                    console.log('CALLBACK callCustomAuthHandler');
                },
                error: function (err) {
                    console.log(err);
                }
            });

        }

    } else {
        if (document.referrer.indexOf('cliffordchance.okta-emea.com') == -1 || document.referrer.indexOf('cliffordchance-dev.oktapreview.com') == -1) {
            internalExternal();
        }
        if(window.location.href.match('alerter-finance.html') || window.location.href.match('alerter-energy.html') || window.location.href.match('alerter-c-m.html'))
		{
            $('.wysiwygbox').first().hide();
		}
    }
}

function copyPrefsFromCookie() {
    // Temporary cookie override to correct malformed JSON and offer ad hoc prefs control
    // Stringify cookie content onto global var for filtration
    if (!!$.cookie('oktauser')) {
        // Clean up the escape characters inherited from the Java creation of the cookie
        var sCleanJSON = $.cookie('oktauser').replace('/', '');
        // Add it to the global comparison var as legitimate JSON data
        cc_cpuser_from_cookie = $.parseJSON(sCleanJSON);
        // $.removeCookie('oktauser', { path: '/' });
        // Update the prefs array with changeable test values
        // var aPrefs = ['37117', '37129', '37071', '37073', '37076', '37083', '37884'];
        // cc_cpuser_from_cookie['prefs'] = aPrefs;
        // cc_cpuser_from_cookie['prefs'] = [];
        // $.cookie('oktauser', JSON.stringify(cc_cpuser_from_cookie), {expires: 365, path: '/'});
        // $.cookie('oktauser', cc_cpuser_from_cookie.toString(), {expires: 365, path: '/'});
    } else {
        // Otherwise set blank values onto the filtration array (or it will error wjhen used)
        cc_cpuser_from_cookie = { guid: '', email: '', firstname: '', lastname: '', prefs: [] };
    }
}

function internalExternal() {

    // Get the internal redirect URL from the Okta widget
    var sInternalLogin = '';
    var bOktaEnabled = false;

    if ($('div#okta-login-container').length > 0) {
        bOktaEnabled = true;
        sInternalLogin = $('section#section_tkosp').attr('data-oktacclogin');
    }

    console.log('Calling internalExternal()');

    $.ajax({
        url: '/cc/ipidentifier?cb=' + Math.random(),
        type: 'GET',
        data: {},
        success: function (res) {
            console.log(res);
            var aIntExt = $.parseJSON(res);
            console.log(aIntExt['ip']);
            console.log(aIntExt['status']);
            if (aIntExt['ip'] == 'InternalIp' && aIntExt['status'] == 'LoggedOut') {
                console.log('User is on an INTERNAL IP but is logged out');
                if (bOktaEnabled && window.location.href.indexOf('/client-portal') > -1) {
                    $.cookie.raw = true;
                    var aQueryString = getParams(window.location.href);
                    // If the referrer LoggedOut is there, we should save the page they were trying to access before auto log-in rather than the current URL
                    if (window.location.href.indexOf('referrerloggedout') > -1) {
                        $.cookie('cc_saml_request_path', aQueryString['referrerloggedout'] + '.html', { path: '/' });
                        console.log('Found referrer: ' + aQueryString['referrerloggedout'] + '.html');
                    } else {
                        $.cookie('cc_saml_request_path', window.location.href, { path: '/' });
                        console.log('Did NOT find referrer: ' + aQueryString['referrerloggedout']);
                    }
                    window.location.href = sInternalLogin;
                }
                userStatus('Internal');
            } else if (aIntExt['ip'] == 'InternalIp' && aIntExt['status'] == 'LoggedIn') {
                console.log('User is on an INTERNAL IP and is logged in');
                userStatus('Internal');
            } else if (aIntExt['ip'] == 'ExternalIp' && aIntExt['status'] == 'LoggedOut') {
                console.log('User is on an EXTERNAL IP and is logged out');
                userStatus('External');
            } else if (aIntExt['ip'] == 'ExternalIp' && aIntExt['status'] == 'LoggedIn') {
                console.log('User is on an EXTERNAL IP and is logged in');
                userStatus('External');
            }
        },
        error: function (err) {
            console.log(err);
        }
    });

}


// =================================== Siteimprove start ================================== //

function callsiteimprove() {



    console.log('Calling Siteimprove()');

    $.ajax({
        url: '/cc/ipidentifier?cb=' + Math.random(),
        type: 'GET',
        data: {},
        success: function (res) {
            console.log(res);
            var aIntExt = $.parseJSON(res);
            console.log(aIntExt['ip']);
            console.log(aIntExt['status']);
            if (aIntExt['ip'] == 'InternalIp' && aIntExt['status'] == 'LoggedOut') {

            } else if (aIntExt['ip'] == 'InternalIp' && aIntExt['status'] == 'LoggedIn') {
				$('body').append('<div name="siteimprove" id="siteimprove" />');
				console.log('Internal LoggedIN');
            } else if (aIntExt['ip'] == 'ExternalIp' && aIntExt['status'] == 'LoggedOut') {

            } else if (aIntExt['ip'] == 'ExternalIp' && aIntExt['status'] == 'LoggedIn') {
				$('body').append('<div name="siteimprove" id="siteimprove" />');
                console.log('External LoggedIN');
            }
        },
        error: function (err) {
            console.log(err);
        }
    });

}


// ================================== Siteimrove End ================================= //


// =================================== END: Cookie Service Functions ================================== //



// ================================== CREATE/REMOVE TEST COOKIE ================================= //

function createTestCookie(n) {

    // Default user
    var cc_cpuser_data = '{}';

    // New user, no prefs
    if (n == 1) {
        cc_cpuser_data = '{\"firstname\":\"Dan\",\"redirectUrl\":\"/content/cliffordChance/prefernceForm\",\"organization\":\"Court Three\",\"guid\":\"cliffordchance.com-e559d686c5d8ab0c586abc233aac5cd879ff2e8cd3642066e06272ed5c9cdca6\",\"type\":\"External\",\"email\":\"dan@courtthree.co.uk\",\"lastname\":\"Norman\",\"prefs\":[]}';
        // Returning user, sector, legal area and jurisdiction prefs
    } else if (n == 2) {
        cc_cpuser_data = '{\"firstname\":\"Dan\",\"redirectUrl\":\"/content/cliffordChance/prefernceForm\",\"organization\":\"Court Three\",\"guid\":\"cliffordchance.com-e559d686c5d8ab0c586abc233aac5cd879ff2e8cd3642066e06272ed5c9cdca6\",\"type\":\"External\",\"email\":\"dan@courtthree.co.uk\",\"lastname\":\"Norman\",\"prefs\":[\"37117\", \"37120\", \"37154\", \"37917\", \"37158\", \"37162\", \"37071\", \"37094\"]}';
        // Returning user, sector, legal area and jurisdiction prefs + pending approval for CP
    } else if (n == 3) {
        cc_cpuser_data = '{\"firstname\":\"Dan\",\"redirectUrl\":\"/content/cliffordChance/prefernceForm\",\"organization\":\"Court Three\",\"guid\":\"cliffordchance.com-e559d686c5d8ab0c586abc233aac5cd879ff2e8cd3642066e06272ed5c9cdca6\",\"type\":\"External\",\"email\":\"dan@courtthree.co.uk\",\"lastname\":\"Norman\",\"prefs\":[\"37129\", \"37109\", \"37151\", \"37935\", \"37091\", \"37097\", \"37884-72377\"]}';
        // Returning user, sector, legal area and jurisdiction prefs + approved for CP
    } else if (n == 4 || n == 5) {
        cc_cpuser_data = '{\"firstname\":\"Dan\",\"redirectUrl\":\"/content/cliffordChance/prefernceForm\",\"organization\":\"Court Three\",\"guid\":\"cliffordchance.com-e559d686c5d8ab0c586abc233aac5cd879ff2e8cd3642066e06272ed5c9cdca6\",\"type\":\"External\",\"email\":\"dan@courtthree.co.uk\",\"lastname\":\"Norman\",\"prefs\":[\"37145\", \"37121\", \"44312-80628\", \"37163\", \"37170\", \"37095\", \"37097\"]}';
        // Returing user, sector, legal area, approved for CP and has the CBMCG Pref
    } else if (n == 6) {
        cc_cpuser_data = '{\"firstname\":\"Dan\",\"redirectUrl\":\"/content/cliffordChance/prefernceForm\",\"organization\":\"Court Three\",\"guid\":\"cliffordchance.com-e559d686c5d8ab0c586abc233aac5cd879ff2e8cd3642066e06272ed5c9cdca6\",\"type\":\"External\",\"email\":\"dan@courtthree.co.uk\",\"lastname\":\"Norman\",\"prefs\":[\"37145\", \"37121\", \"37884-72375\", \"37163\", \"37170\", \"37095\", \"37967\"]}';
    }

    // Clean up the escape characters inherited from the Java creation of the cookie
    var sCleanJSON = cc_cpuser_data.replace('/', '');
    // Add it to the global comparison var as legitimate JSON data
    cc_cpuser_from_cookie = $.parseJSON(sCleanJSON);

    $.removeCookie('oktauser', { path: '/' });

    $.cookie.raw = true;
    $.cookie('oktauser', cc_cpuser_data, { expires: 365, path: '/' });

    if (n == 0) {
        $.removeCookie('oktauser', { path: '/' });
        $.removeCookie('cc_clearedmessage', { path: '/' });
        alert('Test cookie removed - you are effectively logged out');
    } else {
        alert('Test cookie created for User ' + n);
    }

    if (n != 5) {
        location.reload(true);
    } else {
        evalLogin(true);
        evalMessageCentre();
    }

}

// ================================== START: LOGIN FUNCTIONS ================================= //

function evalLogin(bUpdateFromServer) {

    if (bUpdateFromServer) {

        // Bookmarks
        if (!!$.cookie('cc_bookmarks')) {
            cc_cpuser_bookmarks = JSON.parse($.cookie('cc_bookmarks'));
        } else {
            cc_cpuser_bookmarks = { 'bookmarks': [] };
        }

        // Update cookie prefs and AA variables
        if (!!$.cookie('oktauser')) {
            // Add it to the global comparison var as legitimate JSON data
            copyPrefsFromCookie();
            // Set convenience vars for user data to pass to AA
            cc_cpuser_userid = cc_cpuser_from_cookie['guid'].split('-')[1];
            cc_cpuser_authstatus = 'Authenticated';
            cc_cpuser_organizationid = cc_cpuser_from_cookie['guid'].split('-')[0];
            cc_cpuser_guid = cc_cpuser_from_cookie['guid'];
            cc_cpuser_usertype = cc_cpuser_from_cookie['type'];
            if ($('form#prefs_form').length > 0) {
                getIAContactViaGUID(cc_cpuser_guid);
            }
        } else {
            // Otherwise set blank values onto the filtration array (or it will error when used)
            cc_cpuser_from_cookie = { guid: '', email: '', firstname: '', lastname: '', prefs: [] };
            // Set convenience vars for user data to pass to AA
            cc_cpuser_userid = 'None';
            cc_cpuser_authstatus = 'Guest';
            cc_cpuser_organizationid = 'None';
            cc_cpuser_usertype = 'None';
            cc_cpuser_guid = 'None';
        }

    }

    // Initial visibility of links and comps
    // ------------------------------------------------------------------------------------------------

    // Reset the state of the links before re-evaluating them
    $('a.ccos_tokeep').each(function () {
        $(this).removeClass('ccos_tokeep');
    });

    $('a.ccos_toremove').each(function () {
        $(this).removeClass('ccos_toremove');
    });

    // Check if the okta cookie exists
    if (!!$.cookie('oktauser')) {
        // Cookie is present so fade up all protected links
        $('.ccos_protected').each(function () {
            // Look for links that do not require any special prefs to see them
            if ($(this).hasClass('ccos_iaid_00000')) {
                $(this).show().animate({ 'opacity': '1.0' }, function () {
                    // Trigger a click on it if it's the first of a multi-list comp
                    if ($(this).parent().hasClass('ul_multilistcontainer_tabs') && $(this).is(':first-child')) {
                        if (bUpdateFromServer) {
                            bTransitionLock = false;
                            $(this).children('a').trigger('click');
                        }
                    }
                });
                // But if the links require a special IA ID...
            } else {
                // Check if we have values on the prefs array of the user cookie
                if (cc_cpuser_from_cookie['prefs'].length > 0) {
                    // Loop over each pref so we can test if it matches the locked link class
                    for (var iii = 0; iii < cc_cpuser_from_cookie['prefs'].length; iii++) {
                        // Check if the looped element has a class that matches the currently looped pref
                        // if ($(this).hasClass('ccos_iaid_' + cc_cpuser_from_cookie['prefs'][iii])) {
                        if ($(this).attr('class').indexOf(cc_cpuser_from_cookie['prefs'][iii]) > -1) {
                            $(this).show().animate({ 'opacity': '1.0' });
                            // Remove the class that marks the element for deletion
                            $(this).removeClass('ccos_toremove');
                            // Remove the class that protects unprotected links from deletion
                            $(this).next('a.ccos_unprotected').removeClass('ccos_tokeep');
                            // Re-call the panel distributor in case any revealed panels
                            redistributePanels();
                            break;

                        } else {
                            // Mark the protected link for deletion becasue the appropriate pref is not available
                            $(this).addClass('ccos_toremove');
                            // Protect the next unprotected link from being removed so that the unprotected link appears in place of the protected link
                            $(this).next('a.ccos_unprotected').addClass('ccos_tokeep');
                            $(this).next('a.ccos_unprotected').show().animate({ 'opacity': '1.0' });
                        }
                    }
                    // We have a cookie but no prefs at all so we should reinstate any unprotected links that follow an authorised link
                } else {
                    // Mark the protected link for deletion because the appropriate pref is not available
                    $(this).addClass('ccos_toremove');
                    // Protect the next unprotected link from being removed so that the unprotected link appears in place of the protected link
                    $(this).next('a.ccos_unprotected').addClass('ccos_tokeep');
                    $(this).next('a.ccos_unprotected').show().animate({ 'opacity': '1.0' });
                }
            }
            // Check for ON24 and call formatter function if required
            if ($(this).attr('href') !== undefined) {
                if ($(this).attr('href').indexOf('event.on24.com') > -1) {
                    $(this).attr('href', formatON24URL($(this)));
                }
            }
        });
        // And remove any links that are for unprotected view only
        $('.ccos_unprotected').each(function () {
            if ($(this).parent().find('.ccos_protected').length == 0) {
                $(this).animate({ 'opacity': '1' }, function () { $(this).show() });
                $(this).addClass('c3_2');
            } else if (!$(this).hasClass('ccos_protected') && !$(this).hasClass('ccos_tokeep')) {
                $(this).animate({ 'opacity': '0' }, function () { $(this).hide() });
                $(this).addClass('c3_2');
            }
        });
        // Remove the elements marked for deletion
        $('.ccos_toremove').animate({ 'opacity': '0' }, function () { $(this).hide() });
    } else {
        // Cookie is not present so fade up unprotected links
        $('.ccos_unprotected').each(function () {
            $(this).show().animate({ 'opacity': '1.0' }, 0);
        });
        // And remove any protected links
        $('.ccos_protected').each(function () {
            if (!$(this).hasClass('ccos_unprotected')) {
                $(this).animate({ 'opacity': '0' }, 0, function () { $(this).hide() });
            }
        });
    }

    // ------------------------------------------------------------------------------------------------

    // Login form visibiltiy
    if (!!$.cookie('oktauser')) {
        // Oktauser cookie might be in place but the presence of the saml_request_path cookie indicates that we have just asked for a saml resource
        if (!!$.cookie('saml_request_path')) {
            // Hide the account controls
            $('div#okta-account-control').hide();
        } else {
            // Cookie IS in place and there is no saml_request_path so hide the log-in form
            $('div#okta-login-container').hide();
            // And change the labelling on the TKOSP button
            $('a#a_tkosp_button').text('Toolkits & Your Account');
            // Cookie IS NOT in place so hide the admin/account controls
            $('div#okta-account-control').show();
        }
    } else {
        // Cookie IS NOT in place so hide the admin/account controls
        $('div#okta-account-control').hide();
    }

    // Call the message centre
    if (!!$.cookie('oktauser')) {
        // Do not call the message centre here, it's called after the cookie is loaded from the custom auth handlers
    } else {
        evalMessageCentre();
    }


}

function evalLoginTriggers() {

    console.log('evalLoginTriggers()');

    // Loop over all multipurpose lists to trigger their AJAX lists
    $('.section_multilistcontainer').each(function () {
        bTransitionLock = false;
        $(this).find('.ul_multilistcontainer_tabs li:visible:first a').trigger('click');

    });

    // Check if the bookmark/share bar is availabel and, if so, correct its status
    if ($('div.div_alertersharebar').length > 0) {
        if (checkBookmarks($('div.div_alertersharebar').find('a.a_bookmark_cp').attr('href')) > -1) {
            $('div.div_alertersharebar').find('a.a_bookmark_cp').trigger('click').addClass('suppression_30');
        }

    }

}

// =================================== END: LOGIN FUNCTIONS ================================== //

//=================================START: TAG MULTI-PURPOSE LIST ================================ //

function loadTagArticleFeeds(thisElement) {
	
	 // Reset the abstract exposure button
    $('form.form_expose_abstract input').prop('checked', false);
    var className = thisElement.attr('class');
    if(className === "link1 selected"){
    	var dataList1Content = $(".dataList_1").html();
    	$('.tagmultipurposelist section .div_multilistcontainer_target').html(dataList1Content);
    }
    else if(className === "link2 selected"){
    	var dataList2Content = $(".dataList_2").html();
    	$('.tagmultipurposelist section .div_multilistcontainer_target').html(dataList2Content);
    }
    else if(className === "link3 selected"){
    	var dataList3Content = $(".dataList_3").html();
    	$('.tagmultipurposelist section .div_multilistcontainer_target').html(dataList3Content);
    }
    else if(className === "link4 selected"){
    	var dataList4Content = $(".dataList_4").html();
    	$('.tagmultipurposelist section .div_multilistcontainer_target').html(dataList4Content);
    }
    else if(className === "link5 selected"){
    	var dataList5Content = $(".dataList_5").html();
    	$('.tagmultipurposelist section .div_multilistcontainer_target').html(dataList5Content);
    }else{
    	var dataList1Content = $(".dataList_1").html();
    	$('.tagmultipurposelist section .div_multilistcontainer_target').html(dataList1Content);
    }
    
 // Store a reference to the localised section
    var thisSection = thisElement.closest('section');
 // Convert the layout to the number of results to show in the initial view
    var sLayout = thisElement.parent().data('layout');
    var sColour = thisElement.parent().data('colour');
    var sShowFilter = thisElement.parent().data('showfilter');
    var nLimit = 3;
    if (sLayout == 'twocolumn') {
        nLimit = 6;
    } else if (sLayout == 'onecolumn_compressed') {
        nLimit = 10;
    }
    //loadingIcon(true, thisSection.find('div.div_multilistcontainer_target'), '', '');
    // Show the standard lists
    thisSection.find('div.div_multilistcontainer_target').slideDown();
    // Hide the Target-based containers
    thisSection.find('div.div_multilistcontainer_adobetarget').slideUp();
    // Define load target for feed
    var thisTarget = thisElement.parent().parent().parent().parent().find('.div_multilistcontainer_target');
    evalLogin(false);
    // We have to wait for the new list to load before we can unlock the tab menu
    bTransitionLock = false;
    // Set the layout class for the target so it respects the CSS, removes the old one but also waits until the new list is loaded
    thisTarget.removeClass('div_multilistcontainer_target_onecolumn').removeClass('div_multilistcontainer_target_twocolumn').removeClass('div_multilistcontainer_target_onecolumn_compressed');
    thisTarget.addClass('div_multilistcontainer_target_' + sLayout);
    thisTarget.find('ul li').css({ 'border-bottom-color': '#' + sColour });
    thisTarget.find('ul li p.p_bookmark_cp').css({ 'background-color': '#' + sColour });
 // Loop over the skimmable objects and group them together by top position
    thisTarget.find('ul.ul_articlelist_cp > li:visible').each(function (i) {
        // Get the offset of each li so we know which ones are adjacent to each other
        var thisOffset = Math.round($(this).offset().top);
        // Store the calculated offset as a class so we can localise the height to row
        $(this).addClass('offset_top_' + thisOffset);
        // Call the height equaliser FROM ARTICLE.js
        equaliseHeights(thisTarget.find('ul.ul_articlelist_cp li.offset_top_' + thisOffset + ':visible'));
        // Should we show the bookmark button?
        if (checkBookmarks($(this).find('p.p_bookmark_cp a.a_bookmark_cp').attr('href')) > -1) {
            $(this).find('p.p_bookmark_cp a.a_bookmark_cp').addClass('suppression_30');
        }
        // Calc initial height of container based on third (or 5th) item offset and height
        if (i == (nLimit - 1)) {
            var nCalculatedHeight = $(this).position().top + $(this).outerHeight(true);
            // alert($(this).text());
            thisTarget.find('ul.ul_articlelist_cp').css({ 'height': nCalculatedHeight + 'px' });
        }

    });
    if (thisTarget.find('ul.ul_articlelist_cp li:visible').length <= nLimit) {
        showMoreVisibility(thisElement, false);
    } else {
        showMoreVisibility(thisElement, true);
    }
    // Create and populate the filter menu...
    if (sShowFilter == 'jurisdiction' || sShowFilter == 'sector' || sShowFilter == 'legal_area') {
        var sDisplayType = (sShowFilter == 'jurisdiction') ? 'Filter by jurisdiction' : (sShowFilter == 'sector') ? 'Filter by sector' : 'Filter by legal area';
        thisTarget.prepend('<form class="form_multilist_filter_jurisdiction"><select class="select_multilist_filter_jurisdiction"><option value="0">' + sDisplayType + '</option><option value="0">Show all</option></select></form>');
        for (var ii = 0; ii < aFilteredTags.length; ii++) {
            thisTarget.find('select.select_multilist_filter_jurisdiction').append('<option value="' + aFilteredTags[ii].replace(/'/g, '&#39;') + '">' + aFilteredTags[ii] + '</option>');
        }
    }
}

// ================================ START: MULTI-PURPOSE LIST ================================ //

function loadArticleFeeds(thisElement) {

    // Reset the abstract exposure button
    $('form.form_expose_abstract input').prop('checked', false);

    // Store a reference to the localised section
    var thisSection = thisElement.closest('section');
    // Store the data source on a simple string var
    var sDataSource = thisElement.data('datasource') + '.html';
    // Convert the layout to the number of results to show in the initial view
    var sLayout = thisElement.parent().data('layout');
    var sDataType = thisElement.parent().data('datatype');
    var sColour = thisElement.parent().data('colour');
    var sShowFilter = thisElement.parent().data('showfilter');
    var nLimit = 3;
    if (sLayout == 'twocolumn') {
        nLimit = 6;
    } else if (sLayout == 'onecolumn_compressed') {
        nLimit = 10;
    }
    // Perform load of straight, non-target feeds
    if (sDataType == 'preferencebased' || sDataType == 'recentarticles' || sDataType == 'bookmarks') {
        // Call function to inject loading icon
        loadingIcon(true, thisSection.find('div.div_multilistcontainer_target'), '', '');
        // Show the standard lists
        thisSection.find('div.div_multilistcontainer_target').slideDown();
        // Hide the Target-based containers
        thisSection.find('div.div_multilistcontainer_adobetarget').slideUp();
        // Define load target for feed
        var thisTarget = thisElement.parent().parent().parent().parent().find('.div_multilistcontainer_target');
        // If the list is bookmarks we have to bust the cache so we declare a cb variable and then randomise it
        var nCB = '000000';
        if (sDataType == 'bookmarks') {
            nCB = Math.random();
            sDataSource = sDataSource + '?cb=' + nCB;
        }
        // Load the HTML feed into the receiver
        thisTarget.load(sDataSource, function () {
            // Check visibility of log-in depenedent links
            evalLogin(false);
            // We have to wait for the new list to load before we can unlock the tab menu
            bTransitionLock = false;
            // Set the layout class for the target so it respects the CSS, removes the old one but also waits until the new list is loaded
            thisTarget.removeClass('div_multilistcontainer_target_onecolumn').removeClass('div_multilistcontainer_target_twocolumn').removeClass('div_multilistcontainer_target_onecolumn_compressed');
            thisTarget.addClass('div_multilistcontainer_target_' + sLayout);
            thisTarget.find('ul li').css({ 'border-bottom-color': '#' + sColour });
            thisTarget.find('ul li p.p_bookmark_cp').css({ 'background-color': '#' + sColour });
            // Filter the articles (see the comments in the function for details)
            var aFilteredTags = filterArticles(thisElement, sDataType, sShowFilter);
            // Loop over the skimmable objects and group them together by top position
            thisTarget.find('ul.ul_articlelist_cp > li:visible').each(function (i) {
                // Get the offset of each li so we know which ones are adjacent to each other
                var thisOffset = Math.round($(this).offset().top);
                // Store the calculated offset as a class so we can localise the height to row
                $(this).addClass('offset_top_' + thisOffset);
                // Call the height equaliser FROM ARTICLE.js
                equaliseHeights(thisTarget.find('ul.ul_articlelist_cp li.offset_top_' + thisOffset + ':visible'));
                // Should we show the bookmark button?
                if (checkBookmarks($(this).find('p.p_bookmark_cp a.a_bookmark_cp').attr('href')) > -1) {
                    $(this).find('p.p_bookmark_cp a.a_bookmark_cp').addClass('suppression_30');
                }
                // Calc initial height of container based on third (or 5th) item offset and height
                if (i == (nLimit - 1)) {
                    var nCalculatedHeight = $(this).position().top + $(this).outerHeight(true);
                    // alert($(this).text());
                    thisTarget.find('ul.ul_articlelist_cp').css({ 'height': nCalculatedHeight + 'px' });
                }

            });
            if (thisTarget.find('ul.ul_articlelist_cp li:visible').length <= nLimit) {
                showMoreVisibility(thisElement, false);
            } else {
                showMoreVisibility(thisElement, true);
            }
            // Create and populate the filter menu...
            if (sShowFilter == 'jurisdiction' || sShowFilter == 'sector' || sShowFilter == 'legal_area') {
                var sDisplayType = (sShowFilter == 'jurisdiction') ? 'Filter by jurisdiction' : (sShowFilter == 'sector') ? 'Filter by sector' : 'Filter by legal area';
                thisTarget.prepend('<form class="form_multilist_filter_jurisdiction"><select class="select_multilist_filter_jurisdiction"><option value="0">' + sDisplayType + '</option><option value="0">Show all</option></select></form>');
                for (var ii = 0; ii < aFilteredTags.length; ii++) {
                    thisTarget.find('select.select_multilist_filter_jurisdiction').append('<option value="' + aFilteredTags[ii].replace(/'/g, '&#39;') + '">' + aFilteredTags[ii] + '</option>');
                }
            }
        });
        // Handle the Target-based feeds differently
    } else {
        // Hide the regular list
        thisSection.find('div.div_multilistcontainer_target').slideUp();
        thisSection.find('div.div_multilistcontainer_adobetarget').not(thisSection.find('div.div_multilistcontainer_adobetarget_' + sDataType)).slideUp();
        thisSection.find('div.div_multilistcontainer_adobetarget_' + sDataType).find('li').css({ 'opacity': '0', 'display': 'block' });
        thisSection.find('ul li').css({ 'border-bottom-color': '#' + sColour });
        thisSection.find('ul li p.p_bookmark_cp').css({ 'background-color': '#' + sColour });
        thisSection.find('div.div_multilistcontainer_adobetarget_' + sDataType).addClass('div_multilistcontainer_target_' + sLayout).slideDown(function () {
            // $(this).find('li').css({'display': 'block'});
            // Loop over the skimmable objects and group them together by top position
            thisSection.find('div.div_multilistcontainer_adobetarget_' + sDataType).find('li:visible').each(function (i) {
                console.log('EQUALISING: ' + $(this).find('strong').text());
                // Get the offset of each li so we know which ones are adjacent to each other
                var thisOffset = Math.round($(this).offset().top);
                // Store the calculated offset as a class so we can localise the height to row
                $(this).addClass('offset_top_' + thisOffset);
                // Call the height equaliser FROM ARTICLE.js
                equaliseHeights(thisSection.find('div.div_multilistcontainer_adobetarget_' + sDataType).find('li.offset_top_' + thisOffset + ':visible'));
                $(this).delay(i * 10).animate({ 'opacity': '1' });
                // Should we show the bookmark button?
                if (checkBookmarks($(this).find('p.p_bookmark_cp a.a_bookmark_cp').attr('href')) > -1) {
                    $(this).find('p.p_bookmark_cp a.a_bookmark_cp').addClass('suppression_30');
                }
            });
            bTransitionLock = false;
            showMoreVisibility(thisElement, false);
        });

    }

}

// ================================ START: MULTI-PURPOSE MULTIFIELD LIST ================================ //

function loadArticleFeedsMulti(thisElement) {
    // Reset the abstract exposure button
    $('form.form_expose_abstract input').prop('checked', false);

    // Store a reference to the localised section
    var thisSection = thisElement.closest('section');
    var targetList =  thisElement.data('targetlist');

    // Hide the regular list
    thisSection.find('div.div_multilistcontainer_target').slideUp();
    thisSection.find('div.div_multilistcontainer_target').filter(thisSection.find('div.'+targetList)).slideDown();

    // Convert the layout to the number of results to show in the initial view
    var sLayout = thisElement.parent().data('layout');
    var sColour = thisElement.parent().data('colour');
    var sShowFilter = thisElement.parent().data('showfilter');
    var selectedElem = thisElement.parent().data('selectedelem');
    var thisTarget = thisElement.parent().parent().parent().parent().find('.div_multilistcontainer_'+selectedElem);
    var nLimit = 3;
    if (sLayout == 'twocolumn') {
        nLimit = 6;
    } else if (sLayout == 'onecolumn_compressed') {
        nLimit = 10;
    }

         //layout functionality

        thisTarget.removeClass('div_multilistcontainer_target_onecolumn').removeClass('div_multilistcontainer_target_twocolumn').removeClass('div_multilistcontainer_target_onecolumn_compressed');
        thisTarget.addClass('div_multilistcontainer_target_' + sLayout);

        //layout equalizer

		var noOfLi = thisTarget.find('ul.ul_articlelist_cp_'+selectedElem+' li:visible');

        if (noOfLi <= nLimit) {
                showMoreVisibility(thisElement, false);
            } else {
                showMoreVisibility(thisElement, true);
            }
            var aFilteredTags="";

    if($('#ifElementExist').length >= 0){
       $('#ifElementExist').remove();
        // Create and populate the filter menu...
            if (sShowFilter == 'jurisdiction' || sShowFilter == 'sector' || sShowFilter == 'legal_area' || sShowFilter == 'None') {
                thisTarget.find('form.form_multilist_filter_jurisdiction').remove();
                aFilteredTags = filterArticlesMulti(thisElement, "", sShowFilter, selectedElem);
                //thisTarget.find('select.select_multilist_filter_jurisdiction').hide();
				if( sShowFilter != "None"){
					var sDisplayType = (sShowFilter == 'jurisdiction') ? 'Filter by jurisdiction' : (sShowFilter == 'sector') ? 'Filter by sector' : 'Filter by legal area';
					thisTarget.prepend('<form id="ifElementExist" class="form_multilist_filter_jurisdiction"><label for="filter'+sShowFilter+'" style="position: absolute;opacity: 0;">Choose a filter</label><select class="select_multilist_filter_jurisdiction" id="filter'+sShowFilter+'"><option value="0">' + sDisplayType + '</option><option value="0">Show all</option></select></form>');
					for (var ii = 0; ii < aFilteredTags.length; ii++) {
						thisTarget.find('select.select_multilist_filter_jurisdiction').append('<option value="' + aFilteredTags[ii].replace(/'/g, '&#39;') + '">' + aFilteredTags[ii] + '</option>');
					}
				}
            }
    }


                thisTarget.find('ul.ul_articlelist_cp > li:visible').each(function (i) {
                // Get the offset of each li so we know which ones are adjacent to each other
                var thisOffset = Math.round($(this).offset().top);
                // Store the calculated offset as a class so we can localise the height to row
                $(this).addClass('offset_top_' + thisOffset);
                // Call the height equaliser FROM ARTICLE.js
                equaliseHeightsMulti(thisTarget.find('ul.ul_articlelist_cp li.offset_top_' + thisOffset + ':visible'));
                // Should we show the bookmark button?
                if (checkBookmarks($(this).find('p.p_bookmark_cp a.a_bookmark_cp').attr('href')) > -1) {
                    $(this).find('p.p_bookmark_cp a.a_bookmark_cp').addClass('suppression_30');
                }
                // Calc initial height of container based on third (or 5th) item offset and height
                if (i == (nLimit - 1)) {
                    var nCalculatedHeight = $(this).position().top + $(this).outerHeight(true);
                    // alert($(this).text());
                    thisTarget.find('ul.ul_articlelist_cp').css({ 'height': nCalculatedHeight + 'px' });
                }

            });


       // thisSection.find('div.div_multilistcontainer_target_' + sDataType).find('li').css({ 'opacity': '0', 'display': 'block' });
        thisSection.find('ul li').css({ 'border-bottom-color': '#' + sColour });
        thisSection.find('ul li p.p_bookmark_cp').css({ 'background-color': '#' + sColour });
        bTransitionLock = false;

}

function filterArticles(thisElement, sDataType, sFilterType) {
    console.log('filterArticles called: ' + sFilterType);
    // Log all the tags we encounter for the filters menu
    var aFilteredTags = [];
    // Keep a count of the matched elements
    var nNumberOfMatches = 0;
    var nFullLiistLimit = 10;
    var bHasMatchLi = false;
    var bHasMatchSpan = false;
    // Set the max limit items to 100 if the list is compressed style
    if (thisElement.parent().parent().parent().parent().find('div.div_multilistcontainer_target').hasClass('div_multilistcontainer_target_onecolumn_compressed')) {
        nFullLiistLimit = 100;
    }
    // Hide it regardless of state so we can show it later as we find a match
    thisElement.parent().parent().parent().parent().find('div.div_multilistcontainer_target').find('ul.ul_articlelist_cp > li').hide();
    // Loop over each article
    thisElement.parent().parent().parent().parent().find('div.div_multilistcontainer_target').find('ul.ul_articlelist_cp > li').each(function (i) {
        // Hold over a reference to the current iterated element
        var targetElement = $(this);
        bHasMatchLi = false;
        // Loop over each tag in the article
        $(this).find('span.span_tag').each(function (ii) {
            // Log the tag so we can put it in the filter menu
            if ($(this).attr('data-ccoriginal') !== undefined) {
                if (sFilterType == 'jurisdiction') {
                    if ($(this).attr('data-ccoriginal').indexOf('jurisdiction') > -1) {
                        if (aFilteredTags.indexOf($(this).text()) == -1) {
                            aFilteredTags.push($(this).text());
                        }
                    }
                } else if (sFilterType == 'sector') {
                    if ($(this).attr('data-ccoriginal').indexOf('sector') > -1) {
                        if (aFilteredTags.indexOf($(this).text()) == -1) {
                            aFilteredTags.push($(this).text());
                        }
                    }
                } else if (sFilterType == 'legal_area') {
                    if ($(this).attr('data-ccoriginal').indexOf('legal_area') > -1) {
                        if (aFilteredTags.indexOf($(this).text()) == -1) {
                            aFilteredTags.push($(this).text());
                        }
                    }
                }

            }
            bHasMatchSpan = false;
            // Bind the IA ID of the looped tag to a var
            var sCCIAID = $(this).data('cciaid');
            // Loop over the stored user prefs (but only if there are some)
            if (cc_cpuser_from_cookie['prefs'].length > 0) {
                for (var iii = 0; iii < cc_cpuser_from_cookie['prefs'].length; iii++) {
                    // Check for a match between the cookie pref and the cciad OR simply check that all articles should be shown because the list unfiltered
                    if (cc_cpuser_from_cookie['prefs'][iii] == sCCIAID || sDataType != 'preferencebased') {
                        // Immediately show and hide the result to prevent snapping
                        targetElement.show().css({ 'opacity': '0' });
                        // Show the current article if a match is found
                        targetElement.delay(nNumberOfMatches * 10).animate({ 'opacity': '1' });
                        bHasMatchLi = true;
                        bHasMatchSpan = true;
                        // End the cookie loop early and move on
                        break;
                    }
                }
            } else {
                // Immediately show and hide the result to prevent snapping
                targetElement.show().css({ 'opacity': '0' });
                // Show the current article if a match is found
                targetElement.delay(nNumberOfMatches * 10).animate({ 'opacity': '1' });
                bHasMatchLi = true;
                bHasMatchSpan = true;
            }
            // Remove the span tag if there's no match
            if (!bHasMatchSpan) {
                $(this).remove();
            }
        });
        // Perform functions based on matches being found
        if (bHasMatchLi) {
            getFlag(targetElement);
            nNumberOfMatches = nNumberOfMatches + 1;
            reorderTags($(this), thisElement.parent().data('hidejurisdictions'));
            removeDuplicates($(this));
            trimTags($(this));
        }
        // Limit the matches
        if (nNumberOfMatches == nFullLiistLimit) {
            return false;
        }

    });
    // Sort and return the filtered tags array for the filter menu
    aFilteredTags.sort();
    return aFilteredTags;
}

function filterArticlesMulti(thisElement, sDataType, sFilterType, selectedElem) {
    console.log('filterArticles called: ' + sFilterType);
    // Log all the tags we encounter for the filters menu
    var aFilteredTags = [];
    // Keep a count of the matched elements
    var nNumberOfMatches = 0;
    var nFullLiistLimit = 30;
    var bHasMatchLi = false;
    var bHasMatchSpan = false;
	if(selectedElem=='manual_1'){selectedTab1+=1;}
	if(selectedElem=='manual_2'){selectedTab2+=1;}
	if(selectedElem=='manual_3'){selectedTab3+=1;}
	if(selectedElem=='manual_4'){selectedTab4+=1;}
	if(selectedElem=='manual_5'){selectedTab5+=1;}
    // Set the max limit items to 100 if the list is compressed style
    if (thisElement.parent().parent().parent().parent().find('div.div_multilistcontainer_target').hasClass('div_multilistcontainer_target_onecolumn_compressed')) {
        nFullLiistLimit = 100;
    }
    // Hide it regardless of state so we can show it later as we find a match
    //thisElement.parent().parent().parent().parent().find('div.div_multilistcontainer_target').find('ul.ul_articlelist_cp > li').hide();
    // Loop over each article
   // thisElement.parent().parent().parent().parent().find('div.div_multilistcontainer_target').find('ul.ul_articlelist_cp > li').each(function (i) {
    thisElement.parent().parent().parent().parent().find('div.div_multilistcontainer_target').find('ul.ul_articlelist_cp_' + selectedElem + '> li').each(function (i) {
        // Hold over a reference to the current iterated element
        var targetElement = $(this);
        bHasMatchLi = false;
        // Loop over each tag in the article
        $(this).find('span.span_tag').each(function (ii) {
            // Log the tag so we can put it in the filter menu
            if ($(this).attr('data-ccoriginal') !== undefined) {
                if (sFilterType == 'jurisdiction') {
                    if ($(this).attr('data-ccoriginal').indexOf('jurisdiction') > -1) {
                        if (aFilteredTags.indexOf($(this).text()) == -1) {
                            aFilteredTags.push($(this).text());
                        }
                    }
                } else if (sFilterType == 'sector') {
                    if ($(this).attr('data-ccoriginal').indexOf('sector') > -1) {
                        if (aFilteredTags.indexOf($(this).text()) == -1) {
                            aFilteredTags.push($(this).text());
                        }
                    }
                } else if (sFilterType == 'legal_area') {
                    if ($(this).attr('data-ccoriginal').indexOf('legal_area') > -1) {
                        if (aFilteredTags.indexOf($(this).text()) == -1) {
                            aFilteredTags.push($(this).text());
                        }
                    }
                }

            }
            bHasMatchSpan = true;
            bHasMatchLi=true;
        });
        // Perform functions based on matches being found
        if (bHasMatchLi) {
            getFlag(targetElement);
            nNumberOfMatches = nNumberOfMatches + 1;

            removeDuplicates($(this));


            if(selectedElem=='manual_1' && selectedTab1==1)
            {trimTags($(this));
            reorderTags($(this), thisElement.parent().data('hidejurisdictions'));}
			else if(selectedElem=='manual_2' && selectedTab2==1)
            {trimTags($(this));
            reorderTags($(this), thisElement.parent().data('hidejurisdictions'));}
			else if(selectedElem=='manual_3' && selectedTab3==1)
            {trimTags($(this));
            reorderTags($(this), thisElement.parent().data('hidejurisdictions'));}
			else if(selectedElem=='manual_4' && selectedTab4==1)
            {trimTags($(this));
            reorderTags($(this), thisElement.parent().data('hidejurisdictions'));}
			else if(selectedElem=='manual_5' && selectedTab5==1)
            {trimTags($(this));
            reorderTags($(this), thisElement.parent().data('hidejurisdictions'));}
            else{}
        }
        // Limit the matches
        if (nNumberOfMatches == nFullLiistLimit) {
            return false;
        }

    });
    // Sort and return the filtered tags array for the filter menu
    aFilteredTags.sort();
    return aFilteredTags;
}

function filterMultiListJurisdiction(thisElement) {
    // We won't need show more for this
    thisElement.parent().parent().parent().children('a.a_showmore').fadeOut();
    // Show all articles so we don't conflict with slow fade ins of long lists
    thisElement.parent().next().children('li').css('opacity', '1').parent().css('height', 'auto');
    // Loop over the list to see what matches
    thisElement.parent().next().children('li').each(function () {
        if ($(this).children('span.span_tag_container_cp').text().indexOf(thisElement.val()) > -1 || thisElement.val() == 0) {
            // $(this).stop().slideDown();
            $(this).show();
        } else {
            // $(this).stop().slideUp();
            $(this).hide();
        }
    });
}

function getFlag(targetElement) {
    // Loop over each tag on the article
    //alert('called');
    targetElement.find('span.span_tag').each(function (i) {

        // Bind the name of the looped tag to a var
        var sCCTagName = $(this).data('cctagname');
        // Extract the tag type so we know if it's a jurisdiction
        var sCCType = $(this).data('cctype');
        if (sCCType != undefined) {
            // If it is a jurisdiction, prepend it with the appropriate flag
            if (sCCType.indexOf('jurisdiction') > -1) {
                $(this).css({
                    'background-image': 'url(/content/dam/cliffordchance/client-portal/flags/flag_' + sCCTagName + '.gif)',
                    'padding-left': '40px',
                    'background-position': '7px center'
                });
            }
        }
    });
}

function trimTags(targetElement) {
    // Loop over each tag on the article
    targetElement.find('span.span_tag_container_cp').each(function (i) {
        // Loop over each tag on the article
        $(this).find('span').each(function (ii) {
            if ($(this).attr('data-cctagname') == 'alerter_ca' || $(this).attr('data-cctagname') == 'blt_portal') {
                $(this).remove();
                return;
            }
        });
        var nTagCount = 0;
        var sAdditionalTags = "";
        var nTotalCount = $(this).find('span').length;
        // Loop over each tag on the article
        $(this).find('span').each(function (ii) {
            if (ii > 1) {
                $(this).hide();
                sAdditionalTags += $(this).text();
                if (ii < nTotalCount - 1) {
                    sAdditionalTags += ', ';
                }
                nTagCount = nTagCount + 1;
            }
        });
        if (nTagCount > 0) {
            $(this).append('<span class="span_tag" title="' + sAdditionalTags + '"><a class="a_moretags" href="#">+' + nTagCount + ' more</a></span>');
        }

    });
}



function positionTabArrow(thisElement) {
    console.log('position tab arrow ' + thisElement);
    // Define reference to the containing nav element
    var eNav = thisElement.parent().parent().parent();
    // Add the arrow if it's not already there
    if (eNav.children('img.img_arrow_cp').length == 0) {
        eNav.append('<img alt="Arrow" class="img_arrow_cp" src="/etc/designs/cc/images/cp_arrow.png" width="30" height="15" />');
    }
    // Calculate the target position of the arrow
    var nButtonPosition = 0;
    if (thisElement.parent().length > 0) {
        nButtonPosition = thisElement.parent().position().left;
    }
    var nButtonWidth = thisElement.width();
    var nArrowLeft = nButtonPosition + (nButtonWidth / 2);
    eNav.children('img').stop().animate({ 'left': nArrowLeft + 'px' });
}

function reorderTags(thisElement, bHideJurisdictions) {
    // Loop over the span tags
    thisElement.find('span.span_tag').each(function () {
        // Check if it's a jurisdiction tag
        if ($(this).data('cctype') != undefined) {
            if ($(this).data('cctype').indexOf('jurisdiction') > -1) {
                // And if it is, bring to the front of the list
                $(this).parent().prepend($(this));
                // And if this tab needs jurisdictions hidden, remove it
                if (bHideJurisdictions) {
                    $(this).remove();
                }
            }
        }
    });
}


function removeDuplicates(thisElement) {
    // Declare an ampty array
    var aTags = [];
    // Loop over the remaining span tags
    thisElement.find('span.span_tag').each(function () {
        // Check if the taext of the tag already exists in the log array
        if ($.inArray($(this).text(), aTags) > -1) {
            // Remove it it already exists
            $(this).remove();
        }
        // Push the value onto the array for comparison next loop round
        aTags.push($(this).text());
    });
}

function resetShowMore(thisElement) {
    // Set the state of the show more button back to expand, normally called by the top tabs when a new list is generated
    thisElement.parent().parent().parent().parent().children('a.a_showmore').data('state', 'expand');
    if (thisElement.parent().attr('data-hideshowmore') == 'true') {
        //alert('true');
        thisElement.parents('section.section_multilistcontainer').find('a.a_showmore').css('opacity', '0');
    } else {
        //alert('false');
        thisElement.parents('section.section_multilistcontainer').find('a.a_showmore').css('opacity', '1');
    }
}

function resetShowMoreMulti(thisElement) {
    // Set the state of the show more button back to expand, normally called by the top tabs when a new list is generated
    thisElement.parent().parent().parent().parent().children('a.a_showmore').data('state', 'expand');
    if (thisElement.parent().attr('data-hideshowmore') == 'true') {
        //alert('true');
        //thisElement.parents('section.section_multilistcontainer').find('a.a_showmore').css('opacity', '0');
		thisElement.parent().parent().parent().parent().children('a.a_showmore').fadeOut();
    } else {
        //alert('false');
       // thisElement.parents('section.section_multilistcontainer').find('a.a_showmore').css('opacity', '1');
	   thisElement.parent().parent().parent().parent().children('a.a_showmore').fadeIn();
    }
}

// Generic Skimmer to equalise heights of ragged content blocks
function equaliseHeightsMulti(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 showMoreVisibility(thisElement, bShow) {
    // Hide the show more button on demand
    if (!bShow) {
        thisElement.parent().parent().parent().parent().children('a.a_showmore').fadeOut();
    } else {
        thisElement.parent().parent().parent().parent().children('a.a_showmore').fadeIn();
    }
}

function expandArticlesCP(thisElement) {
    // Declare var to hold cumulative value
    var nCalculatedHeight = 0;

    var nCalculatedHeight = thisElement.prevAll('div:visible').children('ul').children('li:visible:last').position().top + thisElement.prevAll('div:visible').children('ul').children('li:visible:last').outerHeight(true);

    // Animate the list container to show all items
    thisElement.prevAll('div:visible').children('ul').animate({ 'height': nCalculatedHeight + 'px' }, function () {
        if (thisElement.parent().attr('id') == 'bookmarks') {
            thisElement.slideUp();
            //alert('bookmarks');
        } else {
            //alert('link');
            thisElement.data('state', 'link');
        }
    });
}

function expandAlertersCP(thisElement) {

    if (thisElement.prop('checked')) {

        thisElement.parent().parent().find('div.div_inline_detail').slideDown();
        thisElement.parent().parent().find('ul').css({ 'height': 'auto' });
        thisElement.parent().parent().find('ul').children('li').css({ 'height': 'auto' });

        thisElement.parent().parent().find('div.div_inline_detail').each(function () {
            if ($(this).find('a.arrow_right').length == 0 && !(window.location.href.indexOf('cbg') > -1)) {
                $(this).append('<a target="_blank" style="margin: 0px; margin-bottom: 20px;" href="' + ($(this).prev('a').length == 1 ? $(this).prev('a').attr('href') : $(this).prev().prev('a').attr('href')) + '" class="arrow_right">Go to page</a>');
            }
        });

    } else {
        thisElement.parent().parent().find('div.div_inline_detail').slideUp();
    }

}

// ================================ END: MULTI-PURPOSE LIST ================================ //

// ================================== START: SMART PANELS ================================== //

function redistributePanels() {
    $('ul.ul_smartpanels_cp').each(function () {

        if ($(this).children().length == 3) {
            // Calc ideal width allowing for the two 15px gaps between the 3 panels (padding has to be dynamic because it's different on the different style of panel
            var nNewWidth = parseInt($(this).children('li').css('padding-left')) + parseInt($(this).children('li').css('padding-right')) + 15;
            $(this).children('li').css({ 'width': 'calc(33.3% - ' + nNewWidth + 'px' });
        }
        // Clean up image positions and padding
        $(this).children('li').each(function () {
            if ($(this).parent().hasClass('ul_layout_bottom')) {
                var nImageHeight = $(this).children('img').height();
                $(this).css({ 'padding-bottom': (nImageHeight) + 'px' });
            }
        });
        // Loop over the child <li>s ot read their positions and heightys for the skimmer
        $(this).children('li').each(function () {
            // Get the offset of each li so we know which ones are adjacent to each other
            var thisOffset = Math.round($(this).offset().top);
            // Store the calculated offset as a class so we can localise the height to row
            $(this).addClass('offset_top_' + thisOffset);
            // Call the height equaliser FROM ARTICLE.js
            equaliseHeights($(this).parent().find('li.offset_top_' + thisOffset + ':visible'));
        });
    });
}

// ================================== END: SMART PANELS ================================== //

// ============================== START: IMAGE TEXT BLOCK V3 ============================= //

function initialiseImageTextBlockV3() {
    // Loop over all carousels on the page
    $('ul.ul_imagetextblockv3_cp').each(function () {
        // Register the conainer and the carrier
        var thisContainer = $(this).parent();
        var thisCarrier = $(this);
        // Set the width of the carrier (the count * the width)
        thisCarrier.css({ 'width': (100 * thisCarrier.children('li').length) + '%' });
        // Loop over all child <li>s in each carousel
        $(this).children('li').each(function (i) {
            // Set the width of the <li>s based on width / count (100% - 40 padding - 80 left margin - 80 right margin - 2 left and right border
            if ($(window).width() > 670) {
                $(this).css({ 'width': 'calc(' + (100 / thisCarrier.children('li').length) + '%' + ' - 40px - 80px - 80px - 2px)' });
            } else {
                $(this).css({ 'width': 'calc(' + (100 / thisCarrier.children('li').length) + '%' + ' - 40px - 20px - 20px - 2px)' });
            }
            // Set the container to the height of the first item
            if (i == 0) {
                thisContainer.css({ 'height': $(this).outerHeight(true) + 40 + 'px' });
            }
            reorderTags($(this), false);
            getFlag($(this));
            // Add the circles to control the carousel
            $('ul.ul_imagetextblockv3_cp_dots li.dot_' + i + '').remove();
            thisContainer.children('ul.ul_imagetextblockv3_cp_dots').append('<li class="dot_' + i + '"><a href="#" data-thisid="' + i + '">Dot Link</a></li>');
        });
    });
}

function animateImageTextBlockV3(thisElement, direction) {

    var nTotalArticles = thisElement.parent().find('ul.ul_imagetextblockv3_cp_dots li a').length;
    var nCurrentArticle = thisElement.parent().find('ul.ul_imagetextblockv3_cp_dots li a.selected').data('thisid') + 1;

    if (direction == 'next' && !bAnimationLockCP) {
        if (nCurrentArticle < nTotalArticles) {
            thisElement.parent().find('ul.ul_imagetextblockv3_cp_dots li a.selected').parent().next().children('a').trigger('click');
        } else {
            thisElement.parent().find('ul.ul_imagetextblockv3_cp_dots li:first-child').children('a').trigger('click');
        }
    } else if (direction == 'prev' && !bAnimationLockCP) {
        if (nCurrentArticle > 1) {
            thisElement.parent().find('ul.ul_imagetextblockv3_cp_dots li a.selected').parent().prev().children('a').trigger('click');
        } else {
            thisElement.parent().find('ul.ul_imagetextblockv3_cp_dots li:last-child').children('a').trigger('click');
        }
    }

}

function animateImageTextBlockV3FromDots(thisElement) {
    // Mark the clicked circle black
    thisElement.parent().parent().find('a').removeClass('selected');
    thisElement.addClass('selected');
    // Store the <ul> as a carrier
    var thisCarrier = thisElement.parent().parent().parent().find('ul.ul_imagetextblockv3_cp');
    // Immediately set the animation lock
    bAnimationLockCP = true;
    // Call the animation on the carrier and move it's left margin in increments of 100%
    thisCarrier.animate({
        'margin-left': (parseInt(thisElement.data('thisid')) * -100) + '%'
    }, function () {
        // Update the current article in view
        thisCarrier.data('currentarticle', parseInt(thisElement.data('thisid')) + 1);
        nCurrentArticle = parseInt(thisCarrier.data('currentarticle'));
        // Unlock the animation lock
        bAnimationLockCP = false;
        thisCarrier.parent().animate({ 'height': thisCarrier.children('li:nth-child(' + nCurrentArticle + ')').outerHeight(true) + 40 + 'px' }).css({ 'overflow': 'visible' });
    });

}

// =============================== END: IMAGE TEXT BLOCK V3 ============================== //

// ============================== START: BOOKMARK FUNCTIONS ============================ //

function addBookmark(thisElement) {

    var nIndex = cc_cpuser_bookmarks['bookmarks'].indexOf(thisElement.attr('href'), 0);
    if (nIndex == -1) {

        console.log("Adding TC bookmarks");
        $.ajax({
            url: "/cc/bookmarks",
            type: "Post",
            data: { bookmark_path: thisElement.attr('href'), action: 'add' },
            success: function (res) {
                cc_cpuser_bookmarks['bookmarks'].unshift(thisElement.attr('href'));
                if ($('section#bookmarks').length > 0) {
                    $('section#bookmarks').find('nav ul li a:first').trigger('click');
                }
                thisElement.addClass('suppression_30');
                if (thisElement.attr('href').indexOf('/cbg/')) {
                    alert('Bookmark added.\r\nUse the blue tab in the top right-hand corner of your screen to access and manage your bookmarks.');
                }
            },
            error: function (err) {
                console.log(err);
            }
        });
    } else {
        alert('You have already bookmarked this resource.\r\nUse the blue tab in the top right-hand corner of your screen to access and manage your bookmarks.');
    }


}

function removeBookmark(thisElement) {

    $.ajax({
        url: "/cc/bookmarks",
        type: "Post",
        data: { bookmark_path: thisElement.attr('href'), action: 'remove' },
        success: function (res) {
            var nIndex = cc_cpuser_bookmarks['bookmarks'].indexOf(thisElement.attr('href'), 0);
            cc_cpuser_bookmarks['bookmarks'].splice(nIndex, 1);
            thisElement.parent().parent().animate({ 'opacity': '0' }, function () {
                $(this).slideUp();
            });
            console.log(res)
        },
        error: function (err) {
            console.log(err)
        }
    });

}

function checkBookmarks(sPath) {
    return cc_cpuser_bookmarks['bookmarks'].indexOf(sPath, 0);
}

function copyBoomarksFromCookie() {
    if (!!$.cookie('cc_bookmarks')) {
        var sCleanJSON = $.cookie('cc_bookmarks');
        cc_cpuser_bookmarks = $.parseJSON(sCleanJSON);
    }
}

// ============================== START: MESSAGE CENTRE ============================ //

function showMessageCentre(thisMessage) {
    var sHeadline = (thisMessage.children('h2').length > 0) ? thisMessage.children('h2').html() : '';
    thisMessage.children('h2').html(sHeadline.replace('$$_firstname_$$', sanitiseString(cc_cpuser_from_cookie['firstname'])));
    thisMessage.show();
    $('section#section_cp_messagecentre').animate({ 'top': '0px' });
    $('section#section_cp_messagecentre').attr('data-cookie', thisMessage);

}

function closeMessageCentre(thisElement) {
    if (!!$.cookie('cc_clearedmessage')) {
        $.removeCookie('cc_clearedmessage', { path: '/' });
    }
    $.cookie('cc_clearedmessage', thisElement.parent().data('messagepref'), { expires: 365, path: '/' });
    $('section#section_cp_messagecentre').animate({ 'top': '-424px' });
}

function evalMessageCentre() {
    var bMessageCentreInUse = false;
    var aQueryString = getParams(window.location.href);
    if (!!$.cookie('oktauser')) {
        // If the user has no prefs set
        if (cc_cpuser_from_cookie['prefs'].length == 0) {
            showMessageCentre($('div.div_cp_message_wrapper').first());
            bMessageCentreInUse = true;
            // else they have prefs and we need to check them for message matches
        } else {
            console.log('EvalMessageCentre 3');
            var nClearedMessage = 0;
            if (!!$.cookie('cc_clearedmessage')) {
                nClearedMessage = $.cookie('cc_clearedmessage');
            }
            $('div.div_cp_message_wrapper').each(function (i) {
                if (
                    cc_cpuser_from_cookie['prefs'].indexOf($(this).data('messagepref')) > -1 && nClearedMessage != $(this).data('messagepref')
                    || (aQueryString['referrerloggedin'] != undefined && $(this).data('messagepref') == 'referrerloggedin')
                ) {
                    showMessageCentre($(this));
                    bMessageCentreInUse = true;
                }
            });
        }
    } else {

        $('div.div_cp_message_wrapper').each(function (i) {
            if (aQueryString['referrerloggedout'] != undefined && $(this).data('messagepref') == 'referrerloggedout') {
                showMessageCentre($(this));
                bMessageCentreInUse = true;
            }
        });
    }
    if (!bMessageCentreInUse) {
        $('div.messagecentre').hide();
    }
}

function sanitiseString(s) {
    s = s.replace(/[^a-z0-9áéíóúñü \.,_-]/gim, "");
    return s.trim();
}

// ============================== START: REGULATORS LIST FUNCTIONS ============================ //

function loadRegulators(thisElement) {
    // Only load the regulators list if it's not already loaded
    //alert('clicked');
    if (thisElement.next().children().length == 0) {
        thisElement.next().load(cc_content_path + '/client-portal/feeds/regulators-by-country.html?r=' + thisElement.attr('href') + '&cb=' + Math.random(), function () {
            removeNonMatchingProducts(thisElement.parent());
            // groupRegulators(thisElement.parent());
            // thisElement.nextAll('ul.ul_regulator_types').slideDown();
            //alert(thisElement.next().height());
            thisElement.next().slideToggle();
        });
    } else {
        thisElement.next().children().show();
        thisElement.next().slideToggle();
    }
}

function groupRegulators(thisCountry) {

    // Copy the regulator types to the open country
    $('ul#ul_regulator_types').clone().addClass('ul_regulator_types').attr('id', 'ul_regulator_types_' + thisCountry.attr('id')).appendTo(thisCountry);

    // Loop over the reg types
    thisCountry.find('ul.ul_regulator_types li a').each(function () {
        var sThisRegToMatch = $(this).attr('href');
        var stickyRegType = $(this).parent();
        // Loop over each regulator to check for a match
        thisCountry.find('ul.ul_unfiltered_regulators > li').each(function () {
            var sThisRegs = ($(this).attr('data-category') != null) ? $(this).attr('data-category') : 'None';
            if (sThisRegs.indexOf(sThisRegToMatch) > 0) {
                stickyRegType.find('ul.ul_filtered_regulators').append($(this));
            }
        });
    });
}

function filterCountriesByLetter(thisElement) {
    // Loop over the countries and start hiding those that don't match
    $('ul#ul_regulator_countries > li').each(function () {
        if ($(this).find('a.a_country_name').text().charAt(0) == thisElement.text()) {
            $(this).show();
            thisElement.css('opacity', '1');
        } else if (thisElement.hasClass('a_atoz_all')) {
            //alert('yes');
            $(this).parent().children().show();
        } else {
            $(this).hide();
        }
    });
}

function filterCountriesByTextInput(thisElement) {
    if (thisElement.val() != '') {
        // Loop over the countries and start hiding those that don't match
        $('ul#ul_regulator_countries li').each(function () {
            if ($(this).find('a.a_country_name, a.a_regulator_name').text().toLowerCase().indexOf(thisElement.val().toLowerCase()) > -1) {
                $(this).addClass('showme');
            } else {
                $(this).removeClass('showme');
            }
        });

        $('ul#ul_regulator_countries li').each(function () {
            if ($(this).hasClass('showme')) {
                $(this).show();
            } else {
                $(this).hide();
            }
        });

        $('ul.ul_unfiltered_regulators').each(function () {
            if ($(this).children('.showme').length > 0) {
                $(this).show();
            }
        });
    } else {
        $('ul.ul_unfiltered_regulators').hide();
        $('ul.ul_unfiltered_regulators').children().show();
    }
}

function fadeFilterCountriesByLetter(thisElement) {
    $('ul#ul_regulator_countries > li').each(function () {
        if ($(this).find('a').text().charAt(0) == thisElement.text()) {
            thisElement.css('opacity', '1');
        }
    });

}

function removeNonMatchingProducts(thisElement) {

    var aQueryString = getParams(window.location.href);

    // Look for querystring
    if (aQueryString['product'] != undefined) {

        var sProduct = aQueryString['product'];
        thisElement.find('li').each(function () {
            if ($(this).attr('data-products') != undefined) {
                if ($(this).attr('data-products').indexOf(sProduct) == -1) {
                    $(this).remove();
                }
            } else {
                $(this).remove();
            }
        });
        if (thisElement.children('ul').children('li').length == 0) {
            // thisElement.children('ul').append('<li><a href="#">No regulators available</a></li>');
            thisElement.remove();
        }
    }

}

// ============================== START: SEARCH FUNCTIONS ============================ //

function scrollToSearch() {
    if (window.location.href.indexOf('query=') > -1) {
        $('body, html').stop().animate({ scrollTop: ($('div.parsysmain').offset().top - 160) + 'px' }, 1000);
    }
}

function moveSearchToTop() {
    if (window.location.href.indexOf('query=') > -1) {
        $('div.search2019form').not('div.headersearch').next().prependTo($('div.parsysmain'));
        var thisHeader = $('div.search2019form').not('div.headersearch').prev();
        $('div.search2019form').not('div.headersearch').prependTo($('div.parsysmain'));
        thisHeader.prependTo($('div.parsysmain'));
    }
}

function loadSearches(sFilters, bReadURL, bLoadFacets, filterSearch) {
    console.log('loadSearches(1)');
    if ($('section.section_searchpanel').length > 0) {
        console.log('loadSearches(2)');
        // Extract the querystring into the JS
        var aQueryString = getParams(window.location.href);
        // Iniitially hide any search panels if there is a content type specified in the URL
        if (aQueryString['contenttype'] != undefined && aQueryString['contenttype'] != 'All') {
            var sContentType = aQueryString['contenttype'];
            $('section.section_searchpanel').not('#section_searchpanel_noresults').each(function () {
                if ($(this).attr('data-thispath') != sContentType) {
                    $(this).remove();
                }
            });
        }
        // Declare an array to hold all the paths we need for filter creation
        var aPaths = [];
        var sPaths = "";
        var pathList = "";
        // Loop over any search panels on the page
        $('div.div_searchresultstarget').each(function () {
            // Push the path onto the paths array so we can use it to search for filters
            aPaths.push($(this).parent().data('thispath'));
        });

        // Loop over the paths in the array to format a querystring
        for (var i = 0; i < aPaths.length; i++) {
            sPaths += '&path=' + aPaths[i];
            pathList += aPaths[i] + ',';
        }

        // Store the cumulative paths on the filters container
        $('div.div_searchfilterstarget').attr('data-thispath', sPaths);
        $('div.div_searchfilterstarget').attr('data-thispathList', pathList);
        // loadSearchAJAX($('div.div_searchresultstarget:first'), sFilters, false, false, true, true, bReadURL);
        // Suppress the auto-facets
        loadSearchAJAX($('div.div_searchresultstarget:first'), sFilters, false, false, true, bLoadFacets, bReadURL, true, filterSearch);
    }
}

function loadSearchAJAX(thisElement, sFilters, bAppend, bSortOrder, bTriggerSequence, bLoadFacets, bReadURL, bFirstSort, filterSearch) {
    // Reset the abstract exposure button
    $('form.form_expose_abstract input').prop('checked', false);
    console.log('loadSearchAJAX()');

    // Convenience var to hold a reference to the clicked more button
    var thisMoreButton = thisElement.parent().children('a.a_moreresults');
    // Extract the querystring into the JS
    var aQueryString = getParams(window.location.href);
    // Calculate the offset
    var nThisPage = parseInt(thisMoreButton.attr('data-page'));
    var nThisPageItems = parseInt(thisMoreButton.attr('data-pageitems'));
    // Set up the loading message
    var sOriginalButtonText = thisMoreButton.children('span.span_originaltext').text();
    thisMoreButton.children('span.span_originaltext').text('One moment please').parent().animate({ 'background-color': '#45A5DA', 'color': '#FFFFFF' }).children('img').animate({ 'margin-top': '0px' });
    // Check if there are any inbound filters (and reset the page count accordingly because new filters mean we should start from scratch)
    if (!bAppend || bSortOrder) {
        nThisPage = 1;
        nThisPageItems = 5;
    }


    if(window.location.href.indexOf('&date=') < 0  && sFilters.indexOf('&date=') < 0){
             $('ul.ul_dates').find('li a').each(function (ind, eve){
                if($(this).attr('id').indexOf($('ul.ul_dates').attr('data-defaultDate')) > -1){
                  $(this).parent().addClass('li_search_tagfilter_selected');
                }
             });
         }


    sFilters = getFilters();



    // If we have a tag pre-filter in the URL, we need to append it to the filters list
    if (window.location.href.indexOf('&tags=') > -1 && bReadURL) {
        sFilters = sFilters + '&tags=' + encodeURI(aQueryString['tags']);
    }
    // If we have a date pre-filter in the URL, we need to append it to the filters list
    if (window.location.href.indexOf('&date=') > -1 && bReadURL) {
        sFilters = sFilters + '&date=' + encodeURI(aQueryString['date']);
    }
    // If we have a sort pre-filter in the URL, we need to append it to the filters list
    if (window.location.href.indexOf('&sort=') > -1 && bReadURL) {
        // sFilters = sFilters + '&sort=' + encodeURI(aQueryString['sort']);
        $('form.form_relevance_alpha input').prop('checked', true);
    }
    // Do we need to reset the facets
    var sFacets = '&facets=true';
    if (bLoadFacets == true) {
        sFacets = '&facets=true';
    } else if (bLoadFacets == false) {
        sFacets = '&facets=false';
    }

     var reqPath = '';
     if(aQueryString['contenttype'] != undefined && aQueryString['contenttype'] == 'All' && !bAppend && !bSortOrder){
     reqPath = $('div.div_searchfilterstarget').attr('data-thispathList');
     }else if(bAppend || (aQueryString['contenttype'] != undefined && aQueryString['contenttype'] != 'All') || bSortOrder){
     reqPath = thisElement.parent().data('thispath');
     }

    // Construct the search URL for this call
    var sURL = cc_content_path + '/search-2019/search-2019-results.html?query=' + encodeURI(aQueryString['query']) + '&path=' + encodeURI(reqPath) + '&page=' + nThisPage + '&pageitems=' + nThisPageItems + sFilters + sFacets + encodeURI(thisElement.parent().data('thisappendquery')) + '&_charset_=UTF-8&c=1';

	// var sURL = cc_content_path + '/search-2019/search-2019-results.html?query=' + encodeURI(aQueryString['query']) + '&path=' + encodeURI(thisElement.parent().data('thispath')) + '&page=' + nThisPage + '&pageitems=' + nThisPageItems + sFilters + sFacets + '&_charset_=UTF-8';
    if (typeof aQueryString['query'] === 'undefined') {
        sURL = cc_content_path + '/search-2019/search-2019-results.html?path=' + encodeURI(reqPath) + '&page=' + nThisPage + '&pageitems=' + nThisPageItems + sFilters + sFacets + encodeURI(thisElement.parent().data('thisappendquery')) + '&_charset_=UTF-8&c=2';
        // sURL = cc_content_path + '/search-2019/search-2019-results.html?path=' + encodeURI(thisElement.parent().data('thispath')) + '&page=' + nThisPage + '&pageitems=' + nThisPageItems + sFilters + sFacets + '&_charset_=UTF-8';
    }
    // If we are adjusting sort order, based on the boolean in the function call...
    if (bSortOrder) {
        // ... check if the input is checked - denoting that sort order should be date-based
        if (thisElement.parent().find('form.form_relevance_alpha input').prop('checked')) {
            // sURL = thisElement.parent().attr('data-currenturl') + '&sort=Date';
            sURL = sURL + '&sort=Date';
        } else {
            // ... otherwise remove the sort modyfier
            // sURL = thisElement.parent().attr('data-currenturl').replace('&sort=Date');
            sURL = sURL.replace('&sort=Date');
        }
    } else if(bFirstSort && !bAppend && !bSortOrder){
     sURL = sURL + '&sort=Date';
    }
    else {
        // But if we do not have the boolean to say we are adjusting sort order, we still need to check if it's checked so we can append the sort parameter to the search url
        if (thisElement.parent().find('form.form_relevance_alpha input').prop('checked')) {
            sURL = sURL + '&sort=Date';
        }
    }

    // Disable the search buttons until get response
    $("input.input_home_4_submit").each(function (ind, e){
    $(this).prop('disabled',true);
    });

       var moreFilterEnabled = $('.h4_filter_permanent.h4_more_filters a');


       if(bLoadFacets && !bSortOrder){
        $(moreFilterEnabled).addClass('a_more_filters_enabled');
       $(moreFilterEnabled).parent().animate({ 'height': '300px' });
       loadingIcon(true, $(moreFilterEnabled).parent(), 'Please wait', '');
       }

    // Make the AJAX call to get the results
    $.ajax({
        url: sURL,
        context: document.body
    }).done(function (data) {
        // Send the returned data to the targetted div

        var stringToHtml = thisElement.after("<div id='stringToHtmlConvertDom'> </div>")
        $("#stringToHtmlConvertDom").append(data);
        var htmlData =  $("#stringToHtmlConvertDom").clone();
        $("#stringToHtmlConvertDom").remove();

        responseSplitCategoryWise(thisElement, htmlData, bAppend, nThisPage, nThisPageItems, sURL, sFilters,thisMoreButton,sOriginalButtonText, aQueryString, bLoadFacets, bTriggerSequence, filterSearch);

    }).fail(function (data) {
                $("input.input_home_4_submit").each(function (ind, e){
                $(this).prop('disabled',false);
                });
    });

}

function responseSplitCategoryWise(thisElement, data, bAppend, nThisPage, nThisPageItems, sURL, sFilters,thisMoreButton,sOriginalButtonText, aQueryString, bLoadFacets, bTriggerSequence, filterSearch){

          var filteredFacetData = $(data).find('ul.ul_facetlist').filter( function() {
          return ($(this).attr('data-currentPath') == thisElement.parent().data('thispath'));
           });

         if((filteredFacetData.length || filterSearch) && (!bAppend)){
          thisElement.find('ul.ul_facetlist').each(function (uiIndex, uiEvent){
             $(uiEvent).remove();
          });
         }

         if(filteredFacetData.length){
          $(filteredFacetData).each(function (index, event) {
            thisElement.append(event);
         });
         }

          var filteredData = $(data).find('ul.ul_searchlist').filter( function() {
          return ($(this).attr('data-currentPath') == thisElement.parent().data('thispath'));
           });

         if((filteredData.length || filterSearch) && (!bAppend)){
          thisElement.find('ul.ul_searchlist').each(function (uiIndex, uiEvent){
             $(uiEvent).remove();
          });
         }

       if(filteredData.length){
           $(filteredData).each(function (index, event) {
            removeAndAppend(thisElement, event, bAppend, nThisPage, nThisPageItems, sURL, sFilters);
           });
         }

         if (thisElement.parent().children('div.div_searchresultstarget').find('li').length == 0) {
              thisElement.parent().fadeOut(function () {
                   checkNoResults();
              });
         } else {
              thisElement.parent().fadeIn(function () {
                   checkNoResults();
               });
         }
            loadSearchCopyFilters(thisElement, data, bAppend, nThisPage, nThisPageItems, sURL, sFilters,thisMoreButton,sOriginalButtonText, aQueryString, bLoadFacets, bTriggerSequence, filterSearch);
            thisMoreButton.children('span.span_originaltext').text(sOriginalButtonText).parent().animate({ 'background-color': '#E5E5E5', 'color': '#000000' }).children('img').stop().animate({ 'margin-top': '-102px' });
            evalBookmarkLoop(thisElement);
            removeDates(thisElement);
}

function removeDates(thisElement) {
    if (thisElement.prev().attr('class') != 'form_relevance_alpha') {
        thisElement.find('time').remove();
    }
}

function evalBookmarkLoop(thisTarget) {
    evalLogin(false);
    // Loop over the skimmable objects and group them together by top position
    thisTarget.find('a.a_searchresults_bookmark').each(function (i) {
        // Should we show the bookmark button?
        if (checkBookmarks($(this).attr('href')) > -1) {
            $(this).addClass('suppression_30');
        }
    });
}

function loadSearchCopyFilters(thisElement, data, bAppend, nThisPage, nThisPageItems, sURL, sFilters,thisMoreButton,sOriginalButtonText, aQueryString, bLoadFacets, bTriggerSequence, filterSearch) {
    if (bTriggerSequence) {
        // Find the next list to load
        if (thisElement.parent().next('section').children('div.div_searchresultstarget').length == 1) {
            responseSplitCategoryWise(thisElement.parent().next('section').children('div.div_searchresultstarget'), data, false, nThisPage, nThisPageItems, sURL, sFilters, thisMoreButton, sOriginalButtonText, aQueryString, bLoadFacets, true, filterSearch);
            checkNoResults();
        } else {
            copyFilters(sFilters, aQueryString, thisElement);
                $("input.input_home_4_submit").each(function (ind, e){
                $(this).prop('disabled',false);
                });
        }
    }else if(!bTriggerSequence){
                $("input.input_home_4_submit").each(function (ind, e){
                $(this).prop('disabled',false);
                });
    }
}

function copyFilters(sFilters, aQueryString, thisElement) {

    //alert('firing');
    $('section.section_searchfilterspanel ul.ul_jurisdictions li').remove();
    $('section.section_searchfilterspanel ul.ul_legalareas li').remove();
    $('section.section_searchfilterspanel ul.ul_sectors li').remove();
    $('section.section_searchfilterspanel ul.ul_alerters li').remove();
    $('section.section_searchfilterspanel ul.ul_hottopic li').remove();
    $('section.section_searchfilterspanel ul.ul_contenttype li').remove();
    $('section.section_searchfilterspanel ul.ul_toolkits li').remove();
    //alert('called');
    //alert('alert 0');
    $('#section_searchresults_2019').find('ul.ul_facetlist').each(function () {

        // De-dupe the list of facets before we start counting...
        var aSeen = {};
        $(this).find('li a').each(function () {
            var sHref = $(this).attr('href');
            if (aSeen[sHref]) {
                $(this).parent().remove();
            } else {
                aSeen[sHref] = true;
            }
        });

        //alert('alert 1' + $(this).text());
        //$('section.section_searchfilterspanel ul li').remove();
        $(this).children().each(function () {
            //alert('alert 2' + $(this).text());
            var thisHref = 0;
            var thisCount = 0;
            thisHref = $(this).children().attr('href');
            thisCount = $(this).find('span').text();
            if (thisHref.indexOf('/etc/tags/jurisdiction') > -1) {

                calcBucketCount($(this), $('ul.ul_jurisdictions'), thisHref, thisCount);

                // $(this).appendTo('ul.ul_jurisdictions');
                // appendAlpha($('ul.ul_jurisdictions'));

            } else if (thisHref.indexOf('/etc/tags/legal_area') > -1) {

                calcBucketCount($(this), $('ul.ul_legalareas'), thisHref, thisCount);
                (thisHref.split('/').length == 5) ? $(this).addClass('isparent') : $(this).addClass('ischild');

            } else if (thisHref.indexOf('/etc/tags/sectors') > -1) {

                calcBucketCount($(this), $('ul.ul_sectors'), thisHref, thisCount);
                (thisHref.split('/').length == 5) ? $(this).addClass('isparent') : $(this).addClass('ischild');

            } else if ((thisHref.indexOf('/etc/tags/client_portal/alerter_') > -1) && ($('ul.ul_alerters').html().indexOf('="' + thisHref + '"') == -1)) {
                $(this).appendTo('ul.ul_alerters');
                appendAlpha($('ul.ul_alerters'));
            } else if ((thisHref.indexOf('/etc/tags/client_portal/current_awareness/hot_topic') > -1) && ($('ul.ul_hottopic').html().indexOf('="' + thisHref + '"') == -1)) {
                $(this).appendTo('ul.ul_hottopic');
                appendAlpha($('ul.ul_hottopic'));
            } else if ((thisHref.indexOf('/etc/tags/client_portal/current_awareness/content_type') > -1) && ($('ul.ul_contenttype').html().indexOf('="' + thisHref + '"') == -1)) {
                $(this).appendTo('ul.ul_contenttype');
                appendAlpha($('ul.ul_contenttype'));
            }else if (thisHref.indexOf('/etc/tags/microsites/talking-tech') > -1) {
               calcBucketCount($(this), $('ul.ul_toolkits'), thisHref, thisCount);
            }else {
                $(this).remove();
            }

            // Override to remove the alerter tag from the list
            if (thisHref.indexOf('/etc/tags/client_portal/alerter_ca') > -1) {
                $(this).remove();
            }

        });
    });

    var sURL = cc_content_path + '/search-2019/search-2019-filters.html?query=' + encodeURI(aQueryString['query']) + $('div.div_searchfilterstarget').attr('data-thispath') + sFilters + '&_charset_=UTF-8';
    $('div.div_searchfilterstarget').each(function () {
        $(this).attr('data-currenttags', sFilters);
        var aTags = sFilters.split('&tags=');
        aTags.shift();
        for (i = 0; i < aTags.length; i++) {
            $(this).find('li').each(function (ii) {
                if ($(this).children('a').attr('href') !== undefined && $(this).children('a').attr('data-filtertype') == 'tags') {
                    if (aTags[i].indexOf('&') > -1) {
                        aTags[i] = aTags[i].split('&')[0];
                    }
                    if ($(this).children('a').attr('href').replace('/etc/tags', '') == aTags[i]) {
                        $(this).addClass('li_search_tagfilter_selected');
                        $(this).parent().slideDown(function () {
                            $(this).css({ 'max-height': ($(window).outerHeight(true) - 440) + 'px', 'overflow': 'scroll' });
                            $('div.search2019results').css({ 'min-height': $('section.section_searchfilterspanel').outerHeight(true) + 100 });
                        }).prev().children().addClass('selected');
                    }
                }
            });
        }
        var aYear = sFilters.split('&year=');
        aYear.shift();
        for (i = 0; i < aYear.length; i++) {
            $(this).find('li').each(function (ii) {
                if ($(this).children('a').attr('href') !== undefined) {
                    if ($(this).children('a').attr('href').replace('#', '') == aYear[i]) {
                        $(this).addClass('li_search_tagfilter_selected');
                    }
                }
            });
        }
        var aDate = sFilters.split('&date=');
        aDate.shift();
        for (i = 0; i < aDate.length; i++) {
            $(this).find('li').each(function (ii) {
                if ($(this).children('a').attr('href') !== undefined && $(this).children('a').attr('data-filtertype') == 'date') {
                    var sDate = aDate[i];
                    if (sDate.indexOf('&')) {
                        sDate = sDate.split('&')[0];
                    }
                    if ($(this).children('a').attr('href').replace('#', '') == sDate) {
                        $(this).addClass('li_search_tagfilter_selected');
                        $(this).parent().slideDown(function () {
                            $(this).css({ 'max-height': ($(window).outerHeight(true) - 440) + 'px', 'overflow': 'scroll' });
                            $('div.search2019results').css({ 'min-height': $('section.section_searchfilterspanel').outerHeight(true) + 100 });
                        }).prev().children().addClass('selected');
                    }
                }
            });
        }
        // Regroup the tags
        groupFacets();
        //Call the search analytics prep function (found in the head of page template, analytics JSP)
        searchClickPrep();
        checkNoResults();
        // Hide the more filters button and loading icon
        if ($('h4.h4_more_filters').children('div').length > 0) {
            if ($('h4.h4_more_filters').children('a').hasClass('a_more_filters_enabled')) {
                $('h4.h4_more_filters').children('a').text('- Fewer filters').attr('title', 'Fewer filters will enable search on archived documents older than 5 years').css({ 'color': '#FFFFFF' }).parent().animate({ 'height': '30px', 'background-color': '#45a5da' }, function () {
                    loadingIcon(false, $('h4.h4_more_filters'), '', '');
                });
            } else {
                $('h4.h4_more_filters').children('a').text('+ More filters').attr('title', 'More filters will disable search on documents older than 5 years').css({ 'color': '#000000' }).parent().animate({ 'height': '30px', 'background-color': '#E5E5E5' }, function () {
                    loadingIcon(false, $('h4.h4_more_filters'), '', '');
                });
            }

        }

    });
}

function calcBucketCount(thisElement, thisTarget, thisHref, thisCount) {

    if (thisTarget.html().indexOf('"' + thisHref + '"') == -1) {
        thisElement.appendTo('ul.' + thisTarget.attr('class'));
        appendAlpha(thisTarget);
    } else {
        thisTarget.children('li').each(function () {
            if ($(this).children('a').attr('href') == thisHref) {
                var nExisting = parseInt($(this).children('a').children('span').text().replace('(', '').replace(')', ''));
                var nNew = parseInt(thisCount.replace('(', '').replace(')', ''));
                $(this).children('a').children('span').text('(' + (nExisting + nNew) + ')');
            }
        });
    }

}

function appendAlpha(thisElement) {
    thisElement.children().sort(function (a, b) {
        var a = $(a).text().toUpperCase();
        var b = $(b).text().toUpperCase();
        return (a < b) ? -1 : (a > b) ? 1 : 0;
    }).appendTo(thisElement);
}

function checkNoResults() {
    if ($('section.section_searchpanel:visible').not('#section_searchpanel_noresults').length == 0) {
        $('section#section_searchpanel_noresults').slideDown(function () {
            // $('ul.ul_dates').slideUp();
            // $('ul.ul_dates').parent().slideUp();
            // $('#section_searchfilters_2019 h3').slideUp();
        });
    } else {
        $('section#section_searchpanel_noresults').slideUp(function () {
            // $('html, body').stop().animate({ scrollTop: '550px'});
        });
    }

    if($('.h4_filter_permanent.h4_more_filters a').hasClass('a_more_filters_enabled')){

    // Hide tab if UL does not appear
        $('section#section_searchfilters_2019 h4').each(function () {
            if ($(this).next('ul').children().length < 1) {
                $(this).not('h4.h4_filter_permanent').slideUp(function () {
                    if ($(this).parent().find('h4:visible').length < 1) {
                        $(this).parent().find('h4').hide();
                        $(this).parent().find('ul').hide();
                        $('#section_searchfilters_2019 h3').hide();
                    }
                });
            } else {
                $(this).slideDown();
            }
        });

    }

}

function removeAndAppend(thisElement, data, bAppend, nThisPage, nThisPageItems, sURL, sFilters) {
    thisElement.append(data);
    // getFlag(thisElement.find('ul:last'));
    getFlag(thisElement.find('ul.ul_searchlist'));
    // reorderTags(thisElement.find('ul:last'), false);
    reorderTags(thisElement.find('ul.ul_searchlist'), false);
    // trimTags(thisElement.find('ul:last'));
    trimTags(thisElement.find('ul.ul_searchlist'));
    // Always slide down in case the outer container has been collapsed by another function
    thisElement.fadeIn();
    // Hide the final ul that's been added and slide it down for slick presentation (only for appended data)
    if (bAppend) {
        thisElement.find('ul:last').hide().fadeIn();
    }
    if (thisElement.parent().children('div.div_searchresultstarget').find('li').length == 0) {
        thisElement.parent().fadeOut(function () {
            checkNoResults();
        });
    } else {
        thisElement.parent().fadeIn(function () {
            checkNoResults();
        });
    }
    if (thisElement.find('ul:last').attr('data-morematches') == 'false') {
        thisElement.parent().children('a.a_moreresults').fadeOut();
    } else {
        thisElement.parent().children('a.a_moreresults').fadeIn();
    }
    // Calculate the next page number (but only if we are appending and not resetting)
    var nNextPage = parseInt(thisElement.parent().children('a.a_moreresults').attr('data-page'));
    if (bAppend) {
        nNextPage = nNextPage + 1;
    } else {
        nNextPage = 2;
        // Store the local search url on the container so we can use it later (but this only happens the first time so we don't increment page counts etc)
        thisElement.parent().attr('data-currenturl', sURL);
    }
    // Update the page number held in the "more results" button
    thisElement.parent().children('a.a_moreresults').attr('data-page', nNextPage);
    // Send the count to the span in the header of the group
    thisElement.parent().children('h4').children('span.span_totals').text(thisElement.children('ul.ul_searchlist:last').attr('data-thistotal'));
}

function filterResults(thisElement) {
    // Close any warnings that are already open
    $('div.div_filter_warning').slideUp();
    // Add the immediately selected option
    var sFilters = '';
    // Deselct other filters of this is a date
    if (thisElement.attr('data-filtertype') == 'date') {
        thisElement.parent().parent().find('li.li_search_tagfilter_selected').not(thisElement.parent()).removeClass('li_search_tagfilter_selected');
        thisElement.parent().addClass('li_search_tagfilter_selected');
    } else {
        thisElement.parent().toggleClass('li_search_tagfilter_selected');
    }

    // Then loop over the selected filters to build a string of filters
    $('div.div_searchfilterstarget').find('li.li_search_tagfilter_selected').each(function () {
        sFilters += '&' + $(this).children('a').attr('data-filtertype') + '=' + $(this).children('a').attr('href').replace('#', '').replace('/etc/tags', '');
    });
    loadSearches(sFilters, false, true, true);
}

function filterResultsWarning(thisElement) {
    // Close any warnings that are already open
    // $('div.div_filter_warning').slideUp();
    // Check if the warning already exists
    if (thisElement.parent().find('div.div_filter_warning').length == 0) {
        // Add the warning if required
        thisElement.after('<div class="div_filter_warning"><p>Please note that searches over extended timeframes can run very slowly. <a href="#"><strong>Click here to proceed?</strong></a></p></div>');
    }
    // Open if closed, close if open
    thisElement.next('div.div_filter_warning').slideToggle();
}

function getFilters() {
    var nFilterCount = 0;
    var sFilters = '';
    // Then loop over the selected filters to build a string of filters
    $('div.div_searchfilterstarget').find('li.li_search_tagfilter_selected').each(function () {
        sFilters += '&' + $(this).children('a').attr('data-filtertype') + '=' + $(this).children('a').attr('href').replace('#', '').replace('/etc/tags', '');
        nFilterCount = nFilterCount + 1;
    });
    if (nFilterCount == 0) {
        sFilters = '';
    }
    return sFilters;
}

function predictSearch(thisElement) {
    console.log('predictSearch');
    var eActiveList;
    if ($('div#div_search_predictions').length == 0) {
        eActiveList = $('div#div_search_predictions');
    } else if ($('div#div_search_predictions_nav').length == 0) {
        eActiveList = $('div#div_search_predictions_nav');
    }
    var sQuery = encodeURI(thisElement.val());
    var sQueryForIndex = thisElement.val();
    var nBodyOffset = parseInt($('body').css('padding-top'));
    var nInputHeight = parseInt(thisElement.height());
    if (sQuery.length == 4) {
        console.log('predictSearch: ' + sQueryForIndex);
        if ($('div#div_search_predictions').length == 0) {
            console.log('C1');
            if (!thisElement.parent().parent().parent().hasClass('div_dropdown_find_lawyer')) {
                $('body').append('<div id="div_search_predictions"></div>');
                $('div#div_search_predictions').css({
                    'left': thisElement.offset().left + 'px',
                    'top': (thisElement.offset().top + nInputHeight) + 'px',
                    'width': thisElement.width() + 'px'
                });
            }
        }
        if ($('div#div_search_predictions_nav').length == 0) {
            console.log('C2');
            if (thisElement.parent().parent().parent().hasClass('div_dropdown_find_lawyer')) {
                $('#div_search_predictions_nav').remove();
                thisElement.parent().parent().parent().parent().append('<div id="div_search_predictions_nav"></div>');
                $('div#div_search_predictions_nav').css({
                    'width': thisElement.width() + 'px'
                });
            }
        }
        if (thisElement.parent().parent().parent().hasClass('div_dropdown_find_lawyer')) {
            console.log('C3');
            $('div#div_search_predictions_nav').load(cc_content_path + '/search-2019/search-2019-predictions.html?query=' + sQuery + '&path=/content/cliffordchance/people_and_places/people&_charset_=UTF-8', function () {
                $(this).fadeIn();
            });
        } else if (thisElement.parent().prev().children('input:hidden').length == 1) {
            console.log('C4');
            $('div#div_search_predictions').load(cc_content_path + '/search-2019/search-2019-predictions.html?query=' + sQuery + '&path=' + thisElement.parent().prev().children('input:hidden').val() + '&_charset_=UTF-8', function () {
                $(this).fadeIn();
                $(this).find('a').each(function () {
                    $(this).attr('href', $(this).attr('href').replace('/search-2019', thisElement.parent().prev().children('input:hidden').val()));
                });
            });
        } else {
            console.log('C5');
            $('div#div_search_predictions').load(cc_content_path + '/search-2019/search-2019-predictions.html?query=' + sQuery + '&_charset_=UTF-8', function () {
                $(this).fadeIn();
            });
        }
    } else if (sQuery.length > 4) {
        // Client-side filtration of the seeded results
        $('div#div_search_predictions ul li a').each(function () {
            var nIndex = $(this).text().toLowerCase().indexOf(sQueryForIndex.toLowerCase());
            if (nIndex == -1) {
                $(this).parent().hide();
            } else {
                $(this).parent().show();
                $(this).html($(this).text().substring(0, nIndex) + '<strong>' + $(this).text().substring(nIndex, nIndex + sQueryForIndex.length) + '</strong>' + $(this).text().substring(nIndex + sQueryForIndex.length));
            }
        });
        $('div#div_search_predictions_nav ul li a').each(function () {
            var nIndex = $(this).text().toLowerCase().indexOf(sQueryForIndex.toLowerCase());
            if (nIndex == -1) {
                $(this).parent().hide();
            } else {
                $(this).parent().show();
                $(this).html($(this).text().substring(0, nIndex) + '<strong>' + $(this).text().substring(nIndex, nIndex + sQueryForIndex.length) + '</strong>' + $(this).text().substring(nIndex + sQueryForIndex.length));
            }
        });
    } else {
        $('div#div_search_predictions, div#div_search_predictions_nav').fadeOut();
    }
}

function traversePredictiveSearch(sDirection) {
    var thisSearchList = $('div#div_search_predictions');
    var thisSearchListNav = $('div#div_search_predictions_nav');
    if (sDirection == "Down") {
        if (thisSearchList.find('a.selected').length == 0) {
            $('form.form_filter_search input').blur();
            thisSearchList.find('li:visible a:first').addClass('selected');
        } else {
            thisSearchList.find('li a.selected').parent().nextAll('li:visible').first().children('a').addClass('selected');
            thisSearchList.find('li a.selected').parent().prevAll('li:visible').first().children('a').removeClass('selected');
        }

        if (thisSearchListNav.find('a.selected').length == 0) {
            $('div.div_dropdown_find_lawyer form input').blur();
            thisSearchListNav.find('li:visible a:first').addClass('selected');
        } else {
            thisSearchListNav.find('li a.selected').parent().nextAll('li:visible').first().children('a').addClass('selected');
            thisSearchListNav.find('li a.selected').parent().prevAll('li:visible').first().children('a').removeClass('selected');
        }
    } else {
        if (thisSearchList.find('li:visible a:first').hasClass('selected')) {
            $('form.form_filter_search input.query').focus();
            thisSearchList.find('li:visible a:first').removeClass('selected');
        } else {
            thisSearchList.find('li a.selected').parent().prevAll('li:visible').first().children('a').addClass('selected');
            thisSearchList.find('li a.selected').parent().nextAll('li:visible').first().children('a').removeClass('selected');
        }

        if (thisSearchListNav.find('li a:first').hasClass('selected')) {
            $('div.div_dropdown_find_lawyer form input#query_nav').focus();
            thisSearchList.find('li:visible a:first').removeClass('selected');
        } else {
            thisSearchListNav.find('li a.selected').parent().prevAll('li:visible').first().children('a').addClass('selected');
            thisSearchListNav.find('li a.selected').parent().nextAll('li:visible').first().children('a').removeClass('selected');
        }
    }
}

function switchSortOrder(thisElement) {
    thisElement.closest('section').find('div.div_searchresultstarget').fadeOut(function () {
        loadSearchAJAX(thisElement.closest('section').find('div.div_searchresultstarget'), 'None', false, true, false, false, false);
    });
}

function transferSearch(thisElement) {
    $('.query').val(thisElement.find('input#query_nav').val());
    $('.form_filter_search').attr('action', thisElement.attr('action'));
    // alert(thisElement.attr('action'));
    $('.form_filter_search').submit();
}

function fixFiltrationMenu() {
    if ($(window).width() > 900) {
        if ($('div.search2019filters').length > 0) {
            var nPosition = $('div.search2019filters').closest('article').offset().top - 80;
            if ($(window).scrollTop() > nPosition) {
                //$('div.search2019filters').parent().css('top', ($(window).scrollTop()) - nPosition + 'px');
            } else {
                $('div.search2019filters').parent().css('top', '0px');
            }
        }
        $('div.search2019filters').parent().css({ 'min-width': '0%', 'float': 'left' });
        $('div.search2019filters').show();
    } else {
        //change width of parent filters
        $('div.search2019filters').parent().css({ 'min-width': '100%', 'float': 'none' });

    }
}

function groupFacets() {
    $('section.section_searchfilterspanel > div > ul').each(function (i) {
        $(this).children('li.isparent').each(function (ii) {
            var sParent = $(this).children('a').attr('href');
            var thisParent = $(this);
            $(this).append('<ul></ul>');
            $(this).parent().children('li.ischild').each(function () {
                var sChild = $(this).children('a').attr('href');
                if (sChild.indexOf(sParent) == 0) {
                    thisParent.children('ul').append($(this));
                }
            });
        });
    })
}

function showSearchFilters(thisElement) {
    if (thisElement.hasClass('a_more_filters_enabled')) {
        thisElement.removeClass('a_more_filters_enabled');
        thisElement.parent().animate({ 'height': '300px' }, function () {
            loadingIcon(true, thisElement.parent(), 'Please wait', '');
            // $('a#a_search_tagfilter_3M').parent().removeClass('li_search_tagfilter_selected');

            //filterResults($('a#a_search_tagfilter_3M'));
            // $('a#a_search_tagfilter_5y').parent().slideDown();
            if (thisElement.attr('data-filtertype') == 'date') {
                    thisElement.parent().parent().find('li.li_search_tagfilter_selected').not(thisElement.parent()).removeClass('li_search_tagfilter_selected');
                    thisElement.parent().addClass('li_search_tagfilter_selected');
                }

            $('a#a_search_tagfilter_10y').parent().slideDown();
            $('a#a_search_tagfilter_20y').parent().slideDown();

              // Hide tab if UL does not appear
                $('section#section_searchfilters_2019 h4').not('h4.h4_filter_permanent').each(function () {
                        $(this).slideUp();

                     if ($(this).find('a').hasClass('selected')) {
                          $(this).find('a').removeClass('selected');
                          $(this).next('ul').slideUp();
                      }

                });

        });
        $('h4.h4_more_filters').children('a').text('+ More filters').attr('title', 'More filters will disable search on documents older than 5 years').css({ 'color': '#000000' }).parent().animate({ 'height': '30px', 'background-color': '#E5E5E5' }, function () {
            loadingIcon(false, $('h4.h4_more_filters'), '', '');
        });
    } else {
        thisElement.addClass('a_more_filters_enabled');
        thisElement.parent().animate({ 'height': '300px' }, function () {
            loadingIcon(true, thisElement.parent(), 'Please wait', '');

            if (thisElement.attr('data-filtertype') == 'date') {
                    thisElement.parent().parent().find('li.li_search_tagfilter_selected').not(thisElement.parent()).removeClass('li_search_tagfilter_selected');
                    thisElement.parent().addClass('li_search_tagfilter_selected');
                }
           // filterResults($('a#a_search_tagfilter_3M'));
            // $('a#a_search_tagfilter_5y').parent().slideUp();
            $('a#a_search_tagfilter_10y').parent().slideUp();
            $('a#a_search_tagfilter_20y').parent().slideUp();
        });

 // Hide tab if UL does not appear
                $('section#section_searchfilters_2019 h4').not('h4.h4_filter_permanent').each(function () {
                    if ($(this).next('ul').children().length > 1) {
                        $(this).slideDown();
                    }else{
                        $(this).slideUp();
                    }
                });

        $('h4.h4_more_filters').children('a').text('- Fewer filters').attr('title', 'Fewer filters will enable search on archived documents older than 5 years').css({ 'color': '#FFFFFF' }).parent().animate({ 'height': '30px', 'background-color': '#45a5da' }, function () {
            loadingIcon(false, $('h4.h4_more_filters'), '', '');
        });

    }


}

function evalGMAT() {
    if (!!$.cookie('CC_GMAT_Login')) {
        // Do less
    } else {
        if (typeof cc_cpuser_from_cookie !== 'undefined') {
            if (cc_cpuser_from_cookie['prefs'].indexOf('44312-80628') > -1 || cc_cpuser_from_cookie['prefs'].indexOf('44312-80631') > -1) {
                $.cookie('CC_GMAT_Login', 'True', { expires: 365, domain: 'cliffordchance.com' });
            }
        }
    }
}

function quickFilter(thisElement) {
    window.location.href = window.location.href + '?query=&path=' + $('input.tags_sector').val() + '&tags=' + thisElement.val().replace('/etc/tags', '') + '&date=2y&_charset_=UTF-8&sort=Date';
}

function showQuickView(thisElement) {

    // Current Page
    var sCurrentPage = thisElement.attr('href');
    var nCurrentPage = 0;
    var aNavLinks = [];

    // Work out sizes
    var nIframeWidth = '160%';
    var nIframeMargin = '-80%';

    if ($(window).width() > 1000) {
        nIframeWidth = '1000px';
        nIframeMargin = '-500px';
    }

    if ($('div#div_serachresultblur', window.parent.document).length == 0) {
        $('body').prepend('<div style="position: fixed; top: 0px; left: 0px; width: 50%; height: 100%; z-index: 100000; backdrop-filter: blur(10px); padding-left: 50%; display: none;" id="div_serachresultblur"></div>');
        $('div#div_serachresultblur').fadeIn();
    }

    if ($('iframe#iframe_searchresultpreview', window.parent.document).length == 0) {
        $('div#div_serachresultblur').append('<iframe src="' + sCurrentPage + '" style="border: none; position: relative; width: ' + nIframeWidth + '; height: 80vh; margin-left: ' + nIframeMargin + '; margin-top: 10vh; background-color: rgb(255, 255, 255); border-radius: 12px; overflow: scroll; box-shadow: rgb(51, 51, 51) 0px 0px 20px; display: none;" id="iframe_searchresultpreview"></iframe>');
    } else {
        $('iframe#iframe_searchresultpreview', window.parent.document).fadeOut(200, function () {
            $('iframe#iframe_searchresultpreview', window.parent.document).attr('src', sCurrentPage);
        });
    }

    $('iframe#iframe_searchresultpreview', window.parent.document).attr('data-currentpage', sCurrentPage);

    $('iframe#iframe_searchresultpreview').bind('load', function () {
        loadingIcon(true, $(this).find('body'), '', '');
        if (typeof $(this).attr('data-navlinks') !== typeof undefined && $(this).attr('data-navlinks') !== false) {
            aNavLinks = $(this).attr('data-navlinks').split(',');
        } else {
            aNavLinks = getQuickViewNav(thisElement);
            $(this).attr('data-navlinks', aNavLinks);
        }
        nCurrentPage = aNavLinks.indexOf($('iframe#iframe_searchresultpreview', window.parent.document).attr('data-currentpage'));
        $(this).contents().find('head').append('<base target="_blank">');
        $(this).contents().find('body').css({ 'padding-top': '12px' });
        $(this).contents().find('header#header_main').hide();
        $(this).contents().find('footer#footer_main').hide();
        $(this).contents().find('div.iparys_inherited').hide();
        $(this).contents().find('section#section_tkosp').hide();
        $(this).contents().find('div.cpalertercahomebar').before('<nav id="nav_iframecontrols" style="background-color: #CCCCCC;"><ul><li><a class="a_qv_close" href="#"><span>Close</span></a></li><li><a class="a_qv_prevnext a_qv_next" href="' + aNavLinks[nCurrentPage + 1] + '"><span>Next</span></a></li><li><a class="a_qv_prevnext" href="' + aNavLinks[nCurrentPage - 1] + '"><span>Prev</span></a></li></ul></nav>');
        $(this).fadeIn();
    });

}

function showQuickViewInline(thisElement) {
    // Add a receiver for the inbound data
    if (thisElement.parent().children('div.div_inline_detail').children().length == 0) {
        // thisElement.parent().append('<div class="div_inline_detail"></div>');
        let thisTarget = thisElement.parent().find('div.div_inline_detail');
        thisTarget.load(thisElement.attr('href') + ' #article_cbg_content', function () {
            thisTarget.slideDown();
            let aThisSearchTerm = $('input.query').val().split(' ');
            for (let i = 0; i < aThisSearchTerm.length; i++) {
                if (aThisSearchTerm[i].length > 3) {

                    var s1 = thisTarget.html();

                    // var regEx = '/using/ig';
                    let regExp = new RegExp(aThisSearchTerm[i], 'gi');

                    var s2 = s1.replace(regExp, function (match) {
                        return '<strong style="color: #45A5DA;">' + match + '</strong>';
                    });

                    $(this).html(s2);

                    /*
                    let regExp = new RegExp(aThisSearchTerm[i],"gi");
                    let sSavedHTML = thisTarget.html();
                    $(this).html(sSavedHTML.replace(regExp, '<strong style="color: #45A5DA;">' + aThisSearchTerm[i] + '</strong>'));
                    */
                }
            }

			if(window.location.href.indexOf('/cbg/cbfg') > -1){

				$('div.search2019results ul.ul_searchlist li div.div_inline_detail article.article_wysiwyg p:nth-child(1)').addClass("yourClass");
				}

            if (thisTarget.find('a.arrow_right').length == 0 && !(window.location.href.indexOf('cbg') > -1)) {
                thisTarget.append('<a target="_blank" style="margin: 0px; margin-bottom: 20px;" href="' + thisElement.attr('href') + '" class="arrow_right">Go to page</a>');
            }


        });
    } else {
        let thisTarget = thisElement.parent().find('div.div_inline_detail');
        if (thisTarget.find('a.arrow_right').length == 0 && !(window.location.href.indexOf('cbg') > -1)) {
            thisTarget.append('<a target="_blank" style="margin: 0px; margin-bottom: 20px;" href="' + thisElement.attr('href') + '" class="arrow_right">Go to page</a>');
        }
		if(window.location.href.indexOf('/cbg/cbfg') > -1){
		$('div.search2019results ul.ul_searchlist li div.div_inline_detail article.article_wysiwyg p:nth-child(1)').addClass("yourClass");
		}
        thisTarget.slideToggle();
    }

}

function getQuickViewNav(thisElement) {
    var aLinks = [];
    thisElement.parent().parent().parent().children('ul.ul_searchlist').children('li').children('a').each(function () {
        aLinks.push($(this).attr('href'));
    });
    return aLinks;
}

function hideQuickView() {
    console.log('hideQuickView()');
    $('div#div_serachresultblur').fadeOut(function () { $(this).remove() });
    $('#iframe_searchresultpreview').fadeOut(function () { $(this).remove() });
}

function formatON24URL(thisElement) {
    var sOldURL = thisElement.attr('href');
    var sNewURL = 'http://event.on24.com/interface/registration/autoreg/index.html?';

    if (sOldURL.indexOf('/r/') > -1) {
        var aURL = sOldURL.split('/r/');
        aURL = aURL[1].split('/');
        var sEventID = aURL[0];
        var sKey = aURL[1];
        sNewURL += 'eventid=' + sEventID + '&';
        sNewURL += 'sessionid=1&key=' + sKey + '&';
        sNewURL += 'firstname=' + cc_cpuser_from_cookie['firstname'] + '&';
        sNewURL += 'lastname=' + cc_cpuser_from_cookie['lastname'] + '&';
        sNewURL += 'email=' + cc_cpuser_from_cookie['email'];
        return sNewURL;
    }
}

// ============================== UTILITIES ============================ //

function getParams(url) {
    var params = {};
    var parser = document.createElement('a');
    parser.href = url;
    var query = parser.search.substring(1);
    var vars = query.split('&');
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split('=');
        params[pair[0]] = decodeURIComponent(pair[1]);
    }
    return params;
};

function searchFormValidation(event) {

            if (event.validity.patternMismatch || event.validity.valueMissing) {
                event.setCustomValidity(event.getAttribute('data-thistitle'));
            } else {
                event.setCustomValidity('');
            }

            return true;
 }