// Global vars to hold selected countries/questions
var aJurisdictions = [];
var aQuestions = [];
var aGlossary = [];
var aAllQuestions = [];
// Global vars to track
var nSelectedJurisdictions = 0;
var nSelectedQuestions = 0;
var nMaxJurisdictions = 5;
var nMaxQuestions = 1000;
var nRemainingQuestions = 1000;
var cbg_isAuthor = false;
var aIntExt='';


$(document).ready( function() {

    // ----------------------------------------------------------------------
	// Check instance

    $('div.div_cbg p.p_cbg_utils_share').hide();
	$('div.div_cbg a.a_detail_view').on('click', function(e) {
		$('div.div_cbg p.p_cbg_utils_share').hide();
		if($('.a_cbg_utils').is('#printid')){
			if(window.location.href.indexOf('cbfg') > -1){
			$('#bookid').addClass('bookhide');
			$('#bookid').removeClass('bookshare');
			}
		}
		else {
			$('#bookid').addClass('bookextra');
            $('#bookid').removeClass('bookextrashare');
		}
		

		e.preventDefault();
	});
	$('div.div_cbg a.a_quick_view').on('click', function(e) {
		
		if($('.a_cbg_utils').is('#printid')){
			if(window.location.href.indexOf('cbfg') > -1){
			$('#bookid').addClass('bookshare');
		}
		}else {
			$('#bookid').addClass('bookextrashare');
		}
		$('div.div_cbg p.p_cbg_utils_share').show();
		e.preventDefault();
	});
	if(window.location.href.indexOf('cbfg') > -1){
		
		if($('.a_cbg_utils').is('#printid')){
			$('#bookid').addClass('book');
		}else {
			$('#bookid').addClass('bookextra');
		}
		
	}else{
		if($('.a_cbg_utils').is('#printid')){
			$('#bookid').addClass('bookfix');
		}else {
			$('#bookid').addClass('bookcbmcg');
		}

	}

	cbg_isAuthor = (window.location.hostname.indexOf('author') > -1 || window.location.hostname.indexOf('localhost') > -1) ? true : false;

    // ----------------------------------------------------------------------
	// Pre-click assignment function calls

    loadGlossary();
    preFilterRegions();
    alignTableLayout();

	// ----------------------------------------------------------------------
	// Click/change listeners for buttons/forms

    $('p.p_cbg_utils_share > a').on('click', function(e) {
		$(this).toggleClass('selected');
        $(this).next().slideToggle();
		e.preventDefault();
	});

    $('p.p_cbg_utils_share span a').on('click', function(e) {
		//alert('share button clicked');
       	cbgShareUrl($(this));
        e.preventDefault();
	});

    $('p.p_cbg_utils_print > a').on('click', function(e) {
		window.print();
        e.preventDefault();
	});


    $('p.p_cbg_utils_download a').on('click', function(e) {
		alert('Your download will begin when you click "OK" below. Please note, if you have selected multiple countries and questions, the PDF may take up to to 30 seconds to generate so please do not click the "Download" buttton again or navigate away from this page in the meantime.');
       	cbgPDFDownload($(this));
        e.preventDefault();
	});

	$('article.article_cbg_container section.section_cbg_main ul li.li_country a').on('click', function(e) {
        prepURL($(this));
        // manageCBGTotals($(this), 'J');
		e.preventDefault();
	});

	$('article.article_cbg_container section.section_cbg_main nav.nav_cbg_tabs ul li.li_cbg_1 a').on('click', function() {
		callCBGTab1($(this));
		return false;
	});

	$('article.article_cbg_container section.section_cbg_main nav.nav_cbg_tabs ul li.li_cbg_2 a').on('click', function() {
		callCBGTab2($(this));
        $('html, body').animate({ scrollTop: '0' });
		return false;
	});

	$('article.article_cbg_container section.section_cbg_main nav.nav_cbg_tabs ul li.li_cbg_3 a').on('click', function() {
		callCBGTab3($(this));
        $('html, body').animate({ scrollTop: '0' });
		return false;
	});

	$('div.div_jurisdictions a.a_cbg_next, div.div_report a.a_cbg_back').on('click', function() {
		$('article.article_cbg_container section.section_cbg_main nav.nav_cbg_tabs ul li.li_cbg_2 a').trigger('click');
		return false;
	});

	$('div.div_questions a.a_cbg_next').on('click', function() {
		$('article.article_cbg_container section.section_cbg_main nav.nav_cbg_tabs ul li.li_cbg_3 a').trigger('click');
		return false;
	});

	$('div.div_questions a.a_cbg_back').on('click', function() {
		$('article.article_cbg_container section.section_cbg_main nav.nav_cbg_tabs ul li.li_cbg_1 a').trigger('click');
		return false;
	});

    $('nav.nav_cbg_countries li a').on('click', function() {
        $('nav.nav_cbg_countries li a').removeClass('selected');
		$(this).addClass('selected');
        filterCountries($(this));
		return false;
	});

	$('article.article_cbg_container section.section_cbg_main div.div_questions article.article_cbg_questions ul li a').not('a.a_selectall').on('click', function(e) {
        if (e.hasOwnProperty('originalEvent')) {
        	$(this).next().slideToggle();
            // alert('Real Click');
        } else {
            $(this).next().show();
            loadingIcon(false, $(this).closest('ul'), '', '');
            // alert('Triggered Click');
        }
        prepURL($(this));
		return false;
	});

	$('article.article_cbg_container section.section_cbg_main div.div_questions article.article_cbg_questions ul li a.a_selectall').on('click', function() {
		if ($(this).hasClass('selected')) {
			$(this).closest('ul').find('a.selected').not('a.a_selectall').trigger('click');
			$(this).removeClass('selected');
		} else {
			$(this).closest('ul').find('a').not('a.selected').not('a.a_selectall').trigger('click');
			$(this).addClass('selected');
		}
		return false;
	});

    $('article.article_cbg_questions > a.a_selectall').on('click', function() {
        var targetElement = $(this).next('ul');
        // loadingIcon(true, targetElement, 'Please wait a moment', 'Selecting all questions takes about 10 seconds');
		if ($(this).hasClass('selected')) {
			$(this).next('ul').find('a.selected').not('a.a_selectall').trigger('click');
			$(this).removeClass('selected');
		} else {
			$(this).next('ul').find('a').not('a.selected').not('a.a_selectall').trigger('click');
			$(this).addClass('selected');
		}
		return false;
	});

	$('article.article_cbg_container section.section_cbg_main div.div_report a.a_detail_view').on('click', function() {
		$('article.article_cbg_container section.section_cbg_main div.div_report a.a_quick_view').removeClass('selected');
		$(this).addClass('selected');
		$('div.div_detail_view').slideDown();
		$('div.div_quick_view').slideUp();
        $('div#div_cbg_popup').remove();
        animateCountryScroll();
		return false;
	});

	$('article.article_cbg_container section.section_cbg_main div.div_report a.a_quick_view').on('click', function() {
		$('article.article_cbg_container section.section_cbg_main div.div_report a.a_detail_view').removeClass('selected');
		$(this).addClass('selected');
		$('div.div_detail_view').slideUp();
        $('div#div_cbg_popup').remove();
		loadCBGReport('table');
		return false;
	});

    $('div.div_detail_view').on('click', 'a.a_cbg_read_more', function(e) {
		cbgReadMore($(this));
		e.preventDefault();
	});

    $('body').on('click', 'div.div_detail_view ul.ul_report_detail div.div_report_detail a, div.div_detail_view ul.ul_report_detail div.div_report_intro a, div.div_quick_view article#article_cbg_report table tr a', function(e) {
        if ($(this).attr('href').indexOf('/glossary/') > -1) {
			cbgPopUpGlossary($(this));
        	e.preventDefault();
        } else if ($(this).attr('href').indexOf('/cbg/') > -1 && $(this).attr('href').indexOf('#j=') == -1 && $(this).attr('href').indexOf('/dam/') == -1) {
			cbgLinkControl($(this));
        	e.preventDefault();
        }
    });

    $('div.div_quick_view').on('click', 'table tr td', function(e) {
        //alert('clicked');
        if ($(this).hasClass('extracopy')) {
			cbgQuickView($(this));
        }
        e.preventDefault();
    });

	$('section.section_cbg_main').on('change', 'select#cbg_select_country', function(e) {
        var y=$("section.section_cbg_main option:selected").index()-1;
		cbgSelectDefaultCountry();
		$('article.article_cbg_contacts > div').slideUp();
		$('article.article_cbg_contacts div.div_cbg_contact_' + y).slideDown();
        $('ul#ul_report_countries li a').removeClass('selected');
        var z='ul#ul_report_countries li.cbg_contact_arrow_'+y+ ' a';
        $('ul#ul_report_countries li.cbg_contact_arrow_'+y+ ' a').addClass('selected');
        e.preventDefault();
    });

    $('form#form_cbg_countries input#input_cbg_countries').on('keyup', function(e) {
		filterCountriesByName($(this));
        e.preventDefault();
    });

    $('form#form_cbg_countries').on('change', 'input#input_cbg_all_countries', function() {
		selectAllCountries($(this));
    });

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

    $('body').on('click', 'div#div_cbg_popup a.a_glossary', function(e) {
        cbgSwitchGlossary($(this));
        e.preventDefault();
    });

    $('div.div_detail_view').on('click', 'a.a_cbg_country_arrow_right', function(e) {
		countryScrollArrowControl($(this), 'R');
		e.preventDefault();
	});

    $('div.div_detail_view').on('click', 'a.a_cbg_country_arrow_left', function(e) {
		countryScrollArrowControl($(this), 'L');
		e.preventDefault();
	});

    $('div.div_detail_view').on('click', 'a.a_cbg_backtotop', function(e) {
        $('html, body').animate({'scrollTop': '0px'});
		e.preventDefault();
	});


    // ----------------------------------------------------------------------
	// Post-click assignment function calls

	cbgLogAllQuestions();
    // cbgPreloadReport();

});


$.ajax({
        url: '/cc/ipidentifier?cb=' + Math.random(),
        type: 'GET',
        data: {},
        success: function (res) {
            var regEx = new RegExp("true");
            var customer_logout = regEx.test(localStorage.getItem("Customer_logout"));
            console.log(res);
            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');
            } else if (aIntExt['ip'] == 'InternalIp' && aIntExt['status'] == 'LoggedIn') {
                console.log('User is on an INTERNAL IP and is logged in');
                userStatus('Internal');
            }
            if(window.location.href.includes("/client-portal") && !customer_logout && aIntExt['status'] == 'LoggedOut'){
                $('body').append('<div class="div_loading" style="display: none; position : fixed !important"><h2 style="text-align: center !important;">' + 'Your session has expired' + '</h2><h3 style="display: block; width: 100% !important; font-size: 30px; text-align: center !important; padding-top: 20px !important; color: #000000 !important; line-height: 28px;">' + 'Please Login again.' + '</h3></div>');
                $('body').children('div.div_loading').fadeIn('fast');
                setTimeout(() => { loadingIcon(false, $('body'), '', '');}, 4000);
            } else {
                localStorage.setItem("Customer_logout", false);
            }

            if(window.location.href.includes("%2Fclient-portal%2Fcurrent-awareness") && !customer_logout && aIntExt['status'] == 'LoggedOut'){
                $('body').append('<div class="div_loading" style="display: none; position : fixed !important"><h2 style="text-align: center !important;">' + 'Your session has expired' + '</h2><h3 style="display: block; width: 100% !important; font-size: 30px; text-align: center !important; padding-top: 20px !important; color: #000000 !important; line-height: 28px;">' + 'Please Login again to access this page.' + '</h3></div>');
                $('body').children('div.div_loading').fadeIn('fast');
                setTimeout(() => {
                    loadingIcon(false, $('body'), '', '');
                    window.location.href = '/content/cliffordchance/client-portal.html';
                }, 5000);
            }
        },
        error: function (err) {
            console.log(err);
        }
    });

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

function alignTableLayout() {
	$('table.fixed-table').css('width', $('article#article_cbg_report > table').css('width'));
}

function animateCountryScroll() {
    $('ul.ul_report_countries').each( function() {
		$(this).stop().animate({scrollLeft: '50px'}, function() {
            $(this).stop().animate({scrollLeft: '0px'}, function() {
				countryScrollVisibilityControl($(this));
			});
        });
    });
}

function countryScrollVisibilityControl(thisElement) {
    if (thisElement.scrollLeft() > 0) {
    	thisElement.prev().children('a.a_cbg_country_arrow_left').fadeIn();
    } else {
		thisElement.prev().children('a.a_cbg_country_arrow_left').fadeOut();
    }
    var nWidth = 0;
    thisElement.children().each( function() {
		nWidth += $(this).width();
    });
    if (nWidth > thisElement.width()) {
		thisElement.prev().children('a.a_cbg_country_arrow_right').fadeIn();
    } else {
		thisElement.prev().children('a.a_cbg_country_arrow_right').fadeOut();
    }
    // alert(thisElement.scrollLeft() + ' | ' + (nWidth - thisElement.width()));
    if (thisElement.scrollLeft() == (nWidth - thisElement.width())) {
		thisElement.prev().children('a.a_cbg_country_arrow_right').fadeOut();
    }
}

function countryScrollArrowControl(thisElement, sDirection) {
	if (sDirection == 'R') {
        thisElement.parent().next().stop().animate({'scrollLeft': '+=200px'}, function() {
			countryScrollVisibilityControl(thisElement.parent().next());
		});
    } else {
		thisElement.parent().next().stop().animate({'scrollLeft': '-=200px'}, function() {
			countryScrollVisibilityControl(thisElement.parent().next());
		});
    }
}

function callCBGTab1(thisElement) {
	thisElement.parent().addClass('selected');
	$('nav.nav_cbg_tabs ul li.li_cbg_2, nav.nav_cbg_tabs ul li.li_cbg_3').removeClass('selected');
	$('nav.nav_cbg_tabs ul li.li_cbg_1, nav.nav_cbg_tabs ul li.li_cbg_2').removeClass('completed');
	$('div.div_jurisdictions').slideDown();
	$('div.div_questions').slideUp();
	$('div.div_report').slideUp();
}

function callCBGTab2(thisElement) {
    if ($('article.article_cbg_jurisdictions ul li a.selected').length > 0) {
        thisElement.parent().addClass('selected');
        $('nav.nav_cbg_tabs ul li.li_cbg_1, nav.nav_cbg_tabs ul li.li_cbg_3').removeClass('selected');
        $('nav.nav_cbg_tabs ul li.li_cbg_1').addClass('completed');
        $('div.div_jurisdictions').slideUp();
        $('div.div_questions').slideDown();
        $('div.div_report').slideUp();
    } else {
		alert('Please select at least one jurisdiction before moving on');
    }
}

function callCBGTab3(thisElement) {
    if ($('article.article_cbg_questions ul li a.selected').length > 0 && nRemainingQuestions >= 0) {
        thisElement.parent().addClass('selected');
        $('nav.nav_cbg_tabs ul li.li_cbg_1, nav.nav_cbg_tabs ul li.li_cbg_2').removeClass('selected');
        $('nav.nav_cbg_tabs ul li.li_cbg_2').addClass('completed');
        $('div.div_jurisdictions').slideUp();
        $('div.div_questions').slideUp( function() {
            loadCBGReport('full');
        });
    } else if (nRemainingQuestions < 0) {
		alert('Sorry!\n\nYou have selected more than ' + nMaxJurisdictions + ' jurisdictions in step 1 which limits you to ' + nMaxQuestions + ' questions in step 2.\n\nPlease deselect ' + (nSelectedJurisdictions - nMaxJurisdictions) + ' jurisdictions or deselect ' + (nSelectedQuestions - nMaxQuestions) + ' questions.');
    } else {
		alert('Please select at least one question before moving on');
    }
}

function preFilterRegions() {
    // Bind the available region codes to an array
    var aAvailableRegions = [];
    $('article.article_cbg_jurisdictions ul li a').each( function () {
        if (typeof $(this).data('regioncode') !== 'undefined') {
			aAvailableRegions.push($(this).data('regioncode'));
        }
	});
    $('nav.nav_cbg_countries ul li a').each( function() {
        $(this).hide(0.3);
		for (var i = 0; i < aAvailableRegions.length; i++) {
            if (aAvailableRegions[i].indexOf($(this).data('regioncode')) > -1) {
				$(this).show(1);
            }
        }
    });
}

function filterCountries(thisElement) {
    $('article.article_cbg_jurisdictions ul li a').each( function() {
        if (typeof $(this).data('regioncode') !== 'undefined') {
            if ($(this).data('regioncode').indexOf(thisElement.data('regioncode')) > -1) {
                $(this).css({'opacity': '1'});
            } else {
				$(this).css({'opacity': '0.3'});
            }
        } else {
			$(this).css({'opacity': '0.3'});
        }
    });
}

function filterCountriesByName(thisElement) {
    $('article.article_cbg_jurisdictions ul li a').each( function() {
        if ($(this).text().trim().toLowerCase().indexOf(thisElement.val().toLowerCase().trim()) > -1) {
			$(this).css({'opacity': '1'});
        } else {
            $(this).css({'opacity': '0.3'});
        }
    });
}

function prepURL(thisElement) {

    if (thisElement.parent().hasClass('li_question')) {
        var sToAdd = thisElement.attr('href').split('/XX')[1];
        if (nRemainingQuestions > 0) {
			if (aQuestions.indexOf(sToAdd) == -1) {
                aQuestions.push(sToAdd);
            } else {
                aQuestions.splice(aQuestions.indexOf(sToAdd), 1);
            }
            thisElement.toggleClass('selected');
        } else if (nRemainingQuestions <= 0 && thisElement.hasClass('selected')) {
			thisElement.removeClass('selected');
            aQuestions.splice(aQuestions.indexOf(sToAdd), 1);
        }
    } else if (thisElement.parent().hasClass('li_country')) {
		var sToAdd = thisElement.data('countrycode');
		if (aJurisdictions.indexOf(sToAdd) == -1) {
			aJurisdictions.push(sToAdd);
        } else {
			aJurisdictions.splice(aJurisdictions.indexOf(sToAdd), 1);
        }
        thisElement.toggleClass('selected');
    }

    window.location.hash = 'j=' + aJurisdictions + '&q=' + cbgSortQuestions(aQuestions);

	nSelectedJurisdictions = aJurisdictions.length;
    nSelectedQuestions = aQuestions.length;

	if (nSelectedJurisdictions > 5) {
		nMaxQuestions = 10;
    } else {
		nMaxQuestions = 1000;
    }

    nRemainingQuestions = nMaxQuestions - nSelectedQuestions;

	manageCBGTotals(thisElement);

}

function manageCBGTotals(thisElement) {

    if (nSelectedJurisdictions <= nMaxJurisdictions) {
		$('li.li_cbg_2 a span.span_cbg_limit').text('');
	} else if (nSelectedJurisdictions == (nMaxJurisdictions + 1)) {
        if (thisElement.hasClass('selected') && thisElement.parent().hasClass('li_country')) {
        	alert('You have selected more than 5 countries. This limits you to a maximum of 10 questions in the next stage.');
        }
        if (nRemainingQuestions < 0) {
			$('li.li_cbg_2 a span.span_cbg_limit').text('Sorry, you have selected ' + Math.abs(nRemainingQuestions) + ' too many questions');
        } else {
			$('li.li_cbg_2 a span.span_cbg_limit').text('You have ' + nRemainingQuestions + ' question' + ((nRemainingQuestions != 1) ? 's' : '') + ' left');
        }
    } else if (nSelectedJurisdictions > (nMaxJurisdictions + 1)) {
        if (nRemainingQuestions < 0) {
			$('li.li_cbg_2 a span.span_cbg_limit').text('Sorry, you have selected ' + Math.abs(nRemainingQuestions) + ' too many questions');
        } else {
			$('li.li_cbg_2 a span.span_cbg_limit').text('You have ' + nRemainingQuestions + ' question' + ((nRemainingQuestions != 1) ? 's' : '') + ' left');
        }
    }

}

function loadCBGReport(l) {

    $('div.div_report').slideDown();
    loadingIcon(true, $('div.div_report'), 'Please wait a moment', 'Your report is being generated');

    var sFragment = window.location.hash.replace('#', '');
    var aFragment = sFragment.split('&');

    var j = '';
    var q = '';

    if (aFragment.length == 2) {
    	j = aFragment[0].replace('j=', '');
   		q = aFragment[1].replace('q=', '');
    }

    var sThisReportURL = window.location.href.replace(window.location.hash, '').replace('.html', '/report.html');

    if (l == 'table') {

        $('div.div_quick_view').load(sThisReportURL + '?l=table&j=' + j + '&q=' + q + ' #article_cbg_report', function() {

            loadingIcon(false, $('div.div_report'), '', '');

            $('article.article_cbg_container section.section_cbg_main div.div_report div.div_quick_view article#article_cbg_report table.fixed-table').remove();
			$('article.article_cbg_container section.section_cbg_main div.div_report div.div_quick_view article#article_cbg_report table').clone().addClass('fixed-table').appendTo('div.div_quick_view #article_cbg_report div.table_container');
            cbgReduceQuickViewCopy();
			$('div.div_quick_view').slideDown( function() {
				alignTableLayout();
            });
		});

    } else {

        $('div.div_detail_view').load(sThisReportURL + '?j=' + j + '&q=' + q + ' #article_cbg_report', function() {

            loadingIcon(false, $('div.div_report'), '', '');

			$('p.p_cbg_utils_download a').attr('href', sThisReportURL + '?j=' + j + '&q=' + q);
            $('p.p_cbg_utils a.a_bookmark_cp').attr('href', window.location.href);

            // If there a no intros, hide the quick view button
            /*
            if ($('div.div_report_intro').length == 0) {
				$('a.a_quick_view').fadeOut();
            }
            */
    
            $('article.article_cbg_container section.section_cbg_main div.div_report article#article_cbg_report ul.ul_report_detail').each( function() {
                $(this).children().each( function(i) {
                    $(this).addClass('li_' + i);
                    if ($(this).children('div.div_report_detail').html().indexOf('<table') > -1) {
            			$(this).children('div.div_report_detail').css('column-count', '1');
        			}
                });

            });

            $('article.article_cbg_container section.section_cbg_main div.div_report article#article_cbg_report ul.ul_report_countries').each( function() {
                $(this).children().each( function(i) {
                    $(this).children('a').on('click', function() {
                        $(this).parent().parent().children().children().removeClass('selected');
                        $(this).addClass('selected');
                        //alert(i);
                        $(this).parents('ul').next().children('li').stop().slideUp();
                        $(this).parents('ul').next().children('li.li_' + i).stop().slideDown();
                        $(this).parents('ul').next().children('li.li_' + i).find('p.p_cbg_lastupdated').text('Last updated: ' + $(this).next('span.span_cbg_lastupdated').text());
                        highlightGlossary($(this).parents('ul').next().children('li.li_' + i).children('div.div_report_detail, div.div_report_intro'), 'loadCBGReport(l)');
                        return false;
                    });
                });
            });
    		$('article.article_cbg_container > #article_cbg_contacts').remove();
			$('#article_cbg_contacts').insertAfter('.section_cbg_main');

			$('article.article_cbg_contacts ul.ul_report_countries li').each( function(i) {
				$(this).children('a').click( function() {
				 // alert('clicked');
					$('article.article_cbg_contacts > div').slideUp();
					$('article.article_cbg_contacts div.div_cbg_contact_' + i).slideDown( function() {
						animateCountryScroll();
                  	});
				return false;
				});
			});

            $('article.article_cbg_container section.section_cbg_main div.div_report article#article_cbg_report ul.ul_report_countries li:first-child a').trigger('click');
			$('article.article_cbg_contacts ul.ul_report_countries li:first-child a').trigger('click');

            // highlightGlossary($('ul.ul_report_detail li:visible div.div_report_detail, ul.ul_report_detail li:visible div_report_intro'));
            cbgBuildSelectMenu();
        });

    }
}

function loadGlossary() {

    var sThisGlossaryURL = window.location.href.replace(window.location.hash, '').replace('.html', '/glossary.html');

    $('div#div_glossary_store').load(sThisGlossaryURL + ' #ul_regulator_glossary', function(data) {
        $('ul#ul_regulator_glossary > li').each( function() {
            console.log('$(this).find(span.span_nohighlight).text(): ' + $(this).find('span.span_nohighlight').text());
			aGlossary.push([$(this).find('span.span_title').text(), $(this).find('span.span_detail').text(), $(this).find('span.span_path').text(), $(this).find('span.span_nohighlight').text()]);
        });
        // highlightGlossary($('ul.ul_report_detail div.div_report_detail, ul.ul_report_detail div_report_intro'), 'loadGlossary()');
        cbgPreloadReport();
    });

}

function highlightGlossary(targetElement, sSource) {
    // Loop over the detail areas of the report
    targetElement.each( function() {

        if ($(this).find('a.a_glossary').length == 0) {

            for (i = 0; i < aGlossary.length; i++) {

               	var s1 = $(this).html();
    
                var regExp = new RegExp('[^a-z]' + aGlossary[i][0] + '(?![^<]*?<\/a>)[^a-z]', 'gi');

                var s2 = s1.replace(regExp, function (match) { 
                    var sFirstMatchedChar = match.substring(0, 1);
                    var sMatchedPhrase = match.substring(1, (match.length - 1));
                    var sMatchedLastChar = match.substring((match.length - 1), (match.length));
                    var sStringToReplace = '';
                    if (aGlossary[i][3] == 'false') {
						sStringToReplace = sFirstMatchedChar + '<a class="a_glossary" href="' + aGlossary[i][2] + '">' + sMatchedPhrase + '</a>' + sMatchedLastChar;
                    } else {
						sStringToReplace = sFirstMatchedChar + '<a class="a_nohighlight">' + sMatchedPhrase + '</a>' + sMatchedLastChar;
                    }
                    return sStringToReplace;
                });

                $(this).html(s2);


				var s3=s2;
                s3 = s3.toLocaleLowerCase();
                var s4 = '<ahref="#"class="close">close</a>';
                s3 = s3.replace(/\s/g,'');

                if(aIntExt['status'] == 'LoggedOut'){  

                    $(this).html("<b>Sorry, you must be logged in. Please login to continue.<b> <a href=\"#\" class=\"close\">Close</a>");

                }

                if(s3.length==s4.length && s3.includes("<ahref")){

                    $(this).html("<b>Sorry, you must be logged in. Please login to continue.<b> <a href=\"#\" class=\"close\">Close</a>");

                }

            }
    	}
        if (cbg_isAuthor) {
        	$(this).html($(this).html().replace('<a>', '<a><span style"color: red !important;">(A)&nbsp;</span>').replace('<b>', '<b><span style"color: red !important;">(B)&nbsp;</span>'));
        }
    });
}

function highlightGlossaryPopUp() {
    // Loop over the detail areas of the report
    $('div#div_cbg_popup').each( function() {
		// And inner loop over the glossary terms
        for (i = 0; i < aGlossary.length; i++) {
            var regExp = new RegExp(aGlossary[i][0], "gi");
            var sSavedHTML = $(this).html();
            $(this).html(sSavedHTML.replace(regExp, '<a class="a_glossary" href="' + aGlossary[i][2] + '">' + aGlossary[i][0] + '</a>'));
        }
    });
}

function cbgPopUpGlossary(thisElement) {
	if ($('div#div_cbg_popup').length == 0) {
        $('body').append('<div id="div_cbg_popup"></div>');
    }
    $('div#div_cbg_popup').css({'top': (thisElement.offset().top + 30) + 'px', 'left': (thisElement.offset().left - 15) + 'px' });
    var nIndexOfTerm = -1;
    for (i = 0; i < aGlossary.length; i++) {
        if (aGlossary[i][0].toLowerCase() == thisElement.text().toLowerCase()) {
			nIndexOfTerm = i;
            break;
        }
    }
    $('div#div_cbg_popup').html('<div id="div_question_content"><article class="article_wysiwyg"><h3>' + aGlossary[nIndexOfTerm][0] + '</h3>' + aGlossary[nIndexOfTerm][1] + '</article></div>');
    $('div#div_cbg_popup').append('<a href="#" class="close">Close</a>');
	$('div#div_cbg_popup').fadeIn();
    highlightGlossary($('div#div_cbg_popup'), 'cbgPopUpGlossary(thisElement)');
}

function cbgSwitchGlossary(thisElement) {
    var nIndexOfTerm = -1;
    for (i = 0; i < aGlossary.length; i++) {
        if (aGlossary[i][0].toLowerCase() == thisElement.text().toLowerCase()) {
            nIndexOfTerm = i;
            break;
        }
    }
    // This needs conditionalising so it can work for inline answers as well as other glossary terms
    thisElement.closest('article.article_wysiwyg').html('<h3>' + aGlossary[nIndexOfTerm][0] + '</h3>' + aGlossary[nIndexOfTerm][1]);
    highlightGlossary($('div#div_cbg_popup'), 'cbgSwitchGlossary(thisElement)');
}


function cbgReadMore(thisElement) {
    if (!thisElement.hasClass('open')) {
        highlightGlossary(thisElement.prev(), 'cbgReadMore(thisElement)');
        thisElement.text(thisElement.attr('data-textwhenopen'));
    	thisElement.addClass('open');
		thisElement.prev().slideDown();
        // thisElement.parent().animate({'padding-bottom': '40px'});
        if (thisElement.prev().children('div.div_report_detail').html().indexOf('<table') > -1) {
            thisElement.prev().children('div.div_report_detail').css('column-count', '1');
        }
    } else {
        thisElement.text(thisElement.attr('data-originaltext'));
		thisElement.removeClass('open');
		thisElement.prev().slideUp();
        // thisElement.parent().animate({'padding-bottom': '30px'});
    }
}

function cbgLinkControl(thisElement) {
    if ($('div#div_cbg_popup').length == 0) {
        $('body').append('<div id="div_cbg_popup"></div>');
    }
    $('div#div_cbg_popup').css({'top': (thisElement.offset().top + 30) + 'px', 'left': (thisElement.offset().left - 15) + 'px' });

    $('div#div_cbg_popup').load(thisElement.attr('href') + ' #div_question_content', function() {
        $('div#div_cbg_popup').append('<a href="#" class="close">Close</a>');
        $('div#div_cbg_popup').fadeIn();
        highlightGlossary($('div#div_cbg_popup'), 'cbgLinkControl(thisElement)');
    });
}

function cbgQuickView(thisElement) {
    $('div#div_cbg_popup').remove();
    $('body').append('<div id="div_cbg_popup" class="quickview"></div>');
    $('div#div_cbg_popup').css({'top': (thisElement.offset().top + 40) + 'px', 'left': (thisElement.offset().left - 191) + 'px' });
    $('div#div_cbg_popup').text(thisElement.attr('data-text'));
    $('div#div_cbg_popup').append('<a href="#" class="close">Close</a>');
    $('div#div_cbg_popup').fadeIn();
}

function cbgPreloadReport() {

    if (location.hash.length > 1) {

		var sFragment = window.location.hash.replace('#', '');
        var aFragments = sFragment.split('&');
        var aJurisdictionsInbound = [];
        var aQuestionsInbound = [];

        for (i = 0; i < aFragments.length; i++) {
            if (aFragments[i].indexOf('j=') == 0) {
                var sThisFragment = aFragments[i].replace('j=', '');
                var aThisFragment = sThisFragment.split(',');
                for (ii = 0; ii < aThisFragment.length; ii++) {
					aJurisdictionsInbound.push(aThisFragment[ii]);
                }

            } else if (aFragments[i].indexOf('q=') == 0) {
                var sThisFragment = aFragments[i].replace('q=', '');
                var aThisFragment = sThisFragment.split(',');
                for (ii = 0; ii < aThisFragment.length; ii++) {
					aQuestionsInbound.push(aThisFragment[ii]);
                }

            }
		}

		aJurisdictions = aJurisdictionsInbound;
		aQuestions = aQuestionsInbound;

        $('article.article_cbg_jurisdictions ul li a').each( function() {
            for (i = 0; i < aJurisdictionsInbound.length; i++) {
                if ($(this).data('countrycode') == aJurisdictionsInbound[i]) {
                    $(this).addClass('selected');
            	}
            }
        });

        $('article.article_cbg_questions ul li a').each( function() {
            for (i = 0; i < aQuestionsInbound.length; i++) {

				if ($(this).attr('href').indexOf('/XX') > -1) {
                    if ($(this).attr('href').split('/XX')[1] == aQuestionsInbound[i]) {
                        $(this).addClass('selected');
                    }
                }
            }
        });

        $('li.li_cbg_3 a').trigger('click');

    }
}

function cbgBuildSelectMenu() {
    $('ul.ul_report_countries').first().find('li a').each( function() {
        $('select#cbg_select_country').append('<option value="' + $(this).data('countrycode') + '">' + $(this).text() + '</option>');
    });
}

function cbgSelectDefaultCountry() {
	$('ul.ul_report_countries li a').each( function() {
        if ($(this).data('countrycode') == $('select#cbg_select_country').val()) {
			$(this).trigger('click');
            $(this).parent().parent().stop().animate({scrollLeft: ($(this).parent().position().left) + ($(this).parent().parent().scrollLeft()) - 40 + 'px' }, function() {
				countryScrollVisibilityControl($(this));
            });
        }
    });
}

function cbgLogAllQuestions() {
    $('article.article_cbg_questions ul li a').each( function() {
		if ($(this).attr('href').indexOf('/XX') > -1) {
			aAllQuestions.push($(this).attr('href').split('/XX')[1]);
		}
    });
}

function cbgSortQuestions(a) {
    var aFinalQuestionArray = [];
    for (i = 0; i < aAllQuestions.length; i++) {
        if (a.includes(aAllQuestions[i])) {
			aFinalQuestionArray.push(aAllQuestions[i]);
        }
	}
    return aFinalQuestionArray;
}

function cbgReduceQuickViewCopy() {
    //alert('working');
    $('div.div_quick_view table tr td').each( function() {
		var thisCharacters = $(this).text().trim();
        var shortenCharacters = thisCharacters.substr(0,197).concat('...');
        //alert(shortenCharacters);
        if (thisCharacters.length > 200) {
            $(this).attr('data-text', thisCharacters);
     		$(this).text(shortenCharacters);
            $(this).addClass('extracopy');
        } 
    });
}

function cbgShareUrl(thisElement) {

    var thisShareURL = thisElement.attr('href').replace('$$_URL_$$', encodeURIComponent(window.location.href));
	window.open(thisShareURL, 'window', 'width = 770, height = 600, left = ' + (screen.availWidth - 770) / 2 + ', top = ' + (screen.availHeight - 600) / 2 + ', scrollbars = yes, location = no, toolbar = no, menubar = no, status = no');

}

function cbgPDFDownload(thisElement) {

   // Replace this with your PDFmyURL license - you get one when you sign up at https://pdfmyurl.com/plans
var license = '';

// First we take the HTML of the page
var html = '<!DOCTYPE html><html lang="en"><head><link href="https://www.cliffordchance.com/etc/designs/cc2014/css/desktop.css" rel="stylesheet" type="text/css" media="screen, print"><link href="https://www.cliffordchance.com/etc/designs/cc/css/style.css" rel="stylesheet" media="screen, print"><link href="https://www.cliffordchance.com/etc/designs/cc/css/style.css" rel="stylesheet" media="print"><link href="https://www.cliffordchance.com/etc/designs/cc/css/print.css" rel="stylesheet" type="text/css" media="print"><link href="https://www.cliffordchance.com/etc/designs/cc/css/cc-cc.css" rel="stylesheet" type="text/css" media="screen"><link href="https://www.cliffordchance.com/etc/designs/cc/css/cp-home.css" rel="stylesheet" type="text/css" media="screen"><link href="https://www.cliffordchance.com/etc/designs/cc/css/cp-prefs.css" rel="stylesheet" type="text/css" media="screen"><link href="https://www.cliffordchance.com/etc/designs/cc/css/cbg.css" rel="stylesheet" type="text/css" media="screen"><link href="https://www.cliffordchance.com/etc/designs/cc/css/cbg-print.css" rel="stylesheet" type="text/css" media="print"></head><body class=" header_overlap" style="width: 1345px !important; padding-left: 5px !important" ><header class="" id="header_marquee">';

html += document.getElementById("header_marquee").innerHTML;
html += '</header>'

var a = document.getElementsByClassName("div_detail_view");
var style = (a[0].getAttribute('style'));
if(style != null && style.indexOf('none') > 0){
	node = document.getElementsByClassName("div_quick_view")[0];
 }

else{
	node = document.getElementsByClassName("div_detail_view")[0];
	}
  
while (node) {
switch (node.nodeType) {
case Node.ELEMENT_NODE:
html += node.outerHTML
break;
case Node.TEXT_NODE:
html += node.nodeValue;
break;
case Node.CDATA_SECTION_NODE:
html += '<![CDATA[' + node.nodeValue + ']]>';
break;
case Node.COMMENT_NODE:
html += '<!--' + node.nodeValue + '-->';
break;
case Node.DOCUMENT_TYPE_NODE:
// (X)HTML documents are identified by public identifiers
html += "<!DOCTYPE " + node.name + (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '') + (!node.publicId && node.systemId ? ' SYSTEM' : '') + (node.systemId ? ' "' + node.systemId + '"' : '') + '>\n';
break;
}
node = node.nextSibling;
}




html+=' </article></body></html>';

html = html.replaceAll('src="/content/dam','src="https://www.yongaandsimiyu.com/content/dam');




// Now we prepare the data that we pass to the API
// We pass the html, our license and custom CSS to hide the PDF button
// Note that you don't need to pass any other parameters if your defaults in our members area are already good
var data = { html: html, license:license, css:'.hide_me{display:none;}'};
var serialized = Object.keys(data).map(function(k) {
return encodeURIComponent(k) + '=' + encodeURIComponent(data[k])
}).join('&')

// You can insert an "in progress" message here

// We now prepare the API call
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
var a;
if (xhttp.readyState === 4 && xhttp.status === 200) {
// The PDF is now generated
// You can remove the "in progress" message here

// Now we show the PDF to the user
var filename = document.title + ".pdf";
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(xhttp.response, filename);
} else {
a = document.createElement('a');
a.href = window.URL.createObjectURL(xhttp.response);
a.download = filename;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
}
}
};

// This is the actual call to our API
xhttp.open("POST","https://pdfmyurl.com/api", true);
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhttp.responseType = 'blob';
xhttp.send(serialized);

}

function selectAllCountries(thisElement) {
    if (thisElement.prop('checked')) {
        $('article.article_cbg_jurisdictions li a').each( function() {
            if (!$(this).hasClass('selected')) {
                $(this).trigger('click');
            }
        });
	} else {
		$('article.article_cbg_jurisdictions li a').each( function() {
            $(this).trigger('click');
        });
	}
}
