/* Minification failed. Returning unminified contents.
(1048,10): run-time error JS1004: Expected ';'
(1049,14): run-time error JS1004: Expected ';'
(1075,10): run-time error JS1004: Expected ';'
(1076,14): run-time error JS1004: Expected ';'
(2880,10): run-time error JS1004: Expected ';'
(2890,41): run-time error JS1004: Expected ';'
(2891,35): run-time error JS1004: Expected ';'
 */
/* Minification failed. Returning unminified contents.
(1039,10): run-time error JS1004: Expected ';'
(1040,14): run-time error JS1004: Expected ';'
(1066,10): run-time error JS1004: Expected ';'
(1067,14): run-time error JS1004: Expected ';'
(2871,10): run-time error JS1004: Expected ';'
(2881,41): run-time error JS1004: Expected ';'
(2882,35): run-time error JS1004: Expected ';'
 */
var FRJournalResearchTopic = (function () {
    var navTabs = {
        key1: 'overview',
        key2: 'articles',
        key3: 'authors'
    };
    if (FRConfiguration.hideImpactTab === "False") {
        navTabs.key4 = 'impact';
    }
    const navTabValues = Object.values(navTabs);
    var $divPageContainer = $('.page-container');
    var $divTopicHeader = $divPageContainer.find('#research-topics-header');
    var $divTabContent = $divPageContainer.find('.tab-content');
    var $divPrimaryTabs = $divTopicHeader.find('.primary-tabs');
    var $divTabOverview = $divTabContent.find('#research-topic-overview');
    var $divTabArticles = $divTabContent.find('#research-topic-articles');
    var $divTabAuthors = $divTabContent.find('#research-topic-authors');
    var $divShareContainer = $divPageContainer.find('.article-share-count'); 
    var FRJournalResearchTopicCommon = (function () {
        $(function () {
            bindEvents();
            loadResearchTopicHeaderImage();
            //manageHashNavigation();
            $(document).trigger('ui.load.images');
            manageTeaserStyles();
            bindGoogleAnalyticsTracking();
        });

        function loadResearchTopicHeaderImage() {
            $.getJSON('/api/research-topics/' + window.FRResearchTopic.Id + '/getResearchTopicHeaderImage').done(function (imageUrl) {
                if (imageUrl && imageUrl.length > 0 && imageUrl != "") {
                    if (document.getElementById('research-topic-image') != null) {
                        document.getElementById('research-topic-image').setAttribute('src', imageUrl);
                    }
                    if (document.getElementById('research-topic-image_NoPreview') != null) {
                        document.getElementById('research-topic-image_NoPreview').setAttribute('src', imageUrl);
                    }
                }
                else {
                    $divTabOverview.find('.more-text-container-img').css('display', 'none');
                }
            });
        }

        function bindEvents() {
            $divPageContainer.on('click', 'button[data-href]', function () {
                if ($(this).hasClass('purchase') && window.FRSocial.loginUserId == 0) {
                    showLoginPopUp();
                } else {
                    if ($(this).hasClass('btn-manage-topic')) { }
                    var href = $(this).data('href');
                    if (!href || !href.length) return;
                    window.location.href = href;
                }
            });
            $divPrimaryTabs.find('#primaryTabs li').on('click', function () {
                    var index = $(this).index();
                    $('#nav_tabs > .tab-pane').removeClass('active in');
                    $('#nav_tabs > .tab-pane:eq(' + index + ')').addClass('active in');
                    var hrefValue = $(this).find('a').attr('href');
                    manageTabNavigation(hrefValue);
            });
            $(window).on('hashchange', function () {
                manageHashNavigation();
                manageTabNavigationOnLoad();
            });
            $(window).on('load', function () {
                manageHashNavigation();
                manageTabNavigationOnLoad();
            });
            $divPageContainer.find('.rt-more-link').click(function () {
                var $divAccordionBodyAboutPreview = $divTabOverview.find('.about-preview');
                if ($(this).hasClass('show-less')) {
                    $divAccordionBodyAboutPreview.collapse('show');
                } else {
                    $divAccordionBodyAboutPreview.collapse('hide');
                }
            });
            $divTabOverview.find('.about-preview').on('hide.bs.collapse', function () {
                var $this = $divPageContainer.find('.rt-more-link');
                $this.text('Show less').addClass('show-less');
            });
            $divTabOverview.find('.about-preview').on('show.bs.collapse', function () {
                var $this = $divPageContainer.find('.rt-more-link');
                $this.text('Show more').removeClass('show-less');
            });
            $(document).on('ui.load.images', function () {
                $divPageContainer.find('img[data-src]').each(function () {
                    var $this = $(this);
                    $this.attr('src', $this.attr('data-src'));
                });
                $divPageContainer.find('img[data-src]').imagesLoaded().progress(function (instance, image) {
                    var $imgCntrl = $(image.img).removeAttr('data-src');
                    if (image.isLoaded) {
                        if ($imgCntrl.hasClass('resize')) {
                            resizeImage($imgCntrl);
                        } else if ($imgCntrl.hasClass('img-clip')) {
                            clipImage($imgCntrl);
                        }
                        $imgCntrl.show();
                    } else {
                        var srcDefault = $imgCntrl.data('default');
                        if (srcDefault && srcDefault.length) {
                            $imgCntrl.attr('src', srcDefault).removeAttr('data-default').imagesLoaded().done(function (instanceAlt) {
                                $(instanceAlt.elements).first().show();
                            });
                        } else {
                            $imgCntrl.closest('.teaser').addClass('no-pic');
                            $imgCntrl.parent('a').remove();
                            $imgCntrl.remove();
                        }
                    }
                });
            });
        }

        function bindGoogleAnalyticsTracking() {
            $divPageContainer.find('.rt-submission .bottom-links li a.authorguidelines').click(function () {
                switch (getCurrentTab()) {
                    case 'overview':
                        break;
                    case 'articles':
                        break;
                }
            });
            $divPageContainer.find('.rt-submission .bottom-links li a.articletypes').click(function () {
                switch (getCurrentTab()) {
                    case 'overview':
                        break;
                    case 'articles':
                        break;
                }
            });
            $divPageContainer.find('.journal-list .bottom-links ul a.submit-abstract').click(function () {
                switch (getCurrentTab()) {
                    case 'overview':
                        break;
                    case 'articles':
                        break;
                }
            });
            $divPageContainer.find('.journal-list .bottom-links ul a.submit-manuscript').click(function () {
                switch (getCurrentTab()) {
                    case 'overview':
                        break;
                    case 'articles':
                        break;
                }
            });
            $divPageContainer.find('.journal-list .teaser a.journal').click(function () {
                switch (getCurrentTab()) {
                    case 'overview':
                        break;
                    case 'articles':
                        break;
                }
            });
            $divPageContainer.find('.journal-list .teaser a.field-journal').click(function () {
                switch (getCurrentTab()) {
                    case 'overview':
                        break;
                    case 'articles':
                        break;
                }
            });
            $divPageContainer.find('.journal-list .teaser a.section').click(function () {
                switch (getCurrentTab()) {
                    case 'overview':
                        break;
                    case 'articles':
                        break;
                }
            });
            $divPageContainer.on('click', '.article-list .articles-wrapper h2.teaser-heading a', function () {
                switch (getCurrentTab()) {
                    case 'overview':
                        break;
                    case 'articles':
                        break;
                }
            });
            $divPageContainer.on('click', '.article-list .articles-wrapper .teaser-authors a', function () {
                switch (getCurrentTab()) {
                    case 'overview':
                        break;
                    case 'articles':
                        break;
                }
            });
            $divPageContainer.on('click', '.profiles.editor-list h2.teaser-heading a', function () {
                switch (getCurrentTab()) {
                    case 'overview':
                        break;
                    case 'articles':
                        break;
                    case 'authors':
                        break;
                }
            });
            $divPageContainer.on('click', '.comment-container h4.teaser-heading a', function () { });
            $divPageContainer.find('#research-topics-header .teaser-buttons li .btn-abstract').click(function () { });
            $divPageContainer.find('#research-topics-header .teaser-buttons li .btn-manuscript').click(function () { });
            $divTabArticles.on('click', '.article-list .articles-wrapper .teaser-links li .altmetric-embed', function () { });
            $divPageContainer.on('click', '.container-editors .teaser-follow .btn-follow-orange', function () {
                switch (getCurrentTab()) {
                    case 'overview':
                        break;
                    case 'articles':
                        break;
                }
            });
            $divPageContainer.on('click', '.container-authors .teaser-follow .btn-follow-orange', function () { });
            $divPageContainer.on('click', '.container-editors .teaser-follow .btn-follow-orange-message', function () { });
        }

        function manageHashNavigation() {
            var hashValue = window.location.hash.replace('#', '').toLowerCase();
            if (!navTabValues.includes(hashValue)) return;
            var urlWithoutHash = window.location.href.split('#')[0];
            var urlsSplits = urlWithoutHash.split('/');
            var tabCheck = urlWithoutHash.split('/')[urlsSplits.length - 1];
            if (navTabValues.includes(tabCheck)) {
                let lastIndex = window.location.pathname.lastIndexOf('/');
                urlWithoutHash = window.location.pathname.substring(0, lastIndex);
            }
            history.replaceState(null, null, history.replaceState(null, null, urlWithoutHash + '/' + hashValue));
        }

        function manageTabNavigation(hrefvalue) {

            var urlsSplits = window.location.href.split('/');
            var tabCheck = urlsSplits[urlsSplits.length - 1].toLowerCase();
            var urlWithoutHash = window.location.href.split('#')[0];
            if (navTabValues.includes(tabCheck)) {
                let lastIndex = window.location.pathname.lastIndexOf('/');
                urlWithoutHash = window.location.pathname.substring(0, lastIndex);
            }
            var slug = hrefvalue.replace("research-topic-", "");
            if (navTabValues.includes(slug)) {
                $divPrimaryTabs.find('a[href="' + hrefvalue + '"]').tab('show');
                $divTabContent.find('div[id="' + '/' + hrefvalue + '"]').tab('show');
                history.replaceState(null, null, history.replaceState(null, null, urlWithoutHash + '/' + slug));
            }
            else
                return;

        }

        function manageTabNavigationOnLoad() {
            var urlsSplits = window.location.href.split('/');
            var tabCheck = urlsSplits[urlsSplits.length - 1].toLowerCase();
            var urlCheck = urlsSplits[urlsSplits.length - 2].toLowerCase();
            if (tabCheck == navTabs.key1) {
                var link = document.createElement('link');
                link.rel = 'canonical';
                let lastIndex = window.location.href.lastIndexOf('/');
                link.href = window.location.href.substring(0, lastIndex);
                document.head.appendChild(link);
            }
            if (navTabValues.includes(tabCheck) && urlCheck !=='') {
                tabCheck = "research-topic-" + tabCheck;
                $divPrimaryTabs.find('a[href="' + tabCheck + '"]').tab('show');
                $divTabContent.find('div[id="' + '/' + tabCheck + '"]').tab('show');
                $('#nav_tabs > .tab-pane').removeClass('active in');
                $('#' + tabCheck).addClass('active in');
            }
        }

        function manageTeaserStyles() {
            $divPageContainer.find('.container-bordered').each(function () {
                var $this = $(this);
                $this.find('.teaser').eq(0).addClass('first');
                $this.find('.teaser-links').last().addClass('last');
            });
        }

        function resizeImage($imgCntrl) {
            var height = parseInt($imgCntrl.css('height'));
            var width = parseInt($imgCntrl.css('width'));
            if (width > 110 && height > 110 && width >= height) {
                $imgCntrl.css('height', 110);
            }
            if (width > 110 && height > 110 && height >= width) {
                $imgCntrl.css('width', 110);
            }
        }

        function clipImage($imgCntrl) {
            if (parseInt($imgCntrl.css('height')) > 250) {
                $imgCntrl.wrap('<div class="img-clip-container"></div>');
            }
        }

        function showLoginPopUp() {
            if ($('.popup-login').length) {
                return;
            }
            var loginPageUrl = window.FRConfiguration.SharepointWebsiteUrl + '/Login.aspx?returnurl=' + document.location.href;
            $.FRModal({
                modalClass: 'popup-login',
                contentHeader: $('<h3>' + 'Login Required' + '</h3>'),
                contentBody: $('<p>This action requires you to be registered with Frontiers and logged in. To register or login click <a href=' + loginPageUrl + '>here.</a> </p>')
            });
        }

        function getCurrentTab() {
            return $divPageContainer.find('.primary-tabs li.active a').attr('class');
        }

        function getPagerHtml(jsnPager) {
            if (!jsnPager || !jsnPager.HasPagination) {
                return '';
            }
            var pageLimit = 6;
            var startIndex = 1;
            var endIndex;
            var $ulPager = $('<ul>');
            if (jsnPager.PageIndex > 3) startIndex = jsnPager.PageIndex - 2;
            var pageDiff = jsnPager.TotalPageCount - jsnPager.PageIndex;
            if (pageDiff < pageLimit) {
                if (pageDiff <= 2) {
                    startIndex = (jsnPager.TotalPageCount - pageLimit + 1);
                }
            }
            if (startIndex <= 0) {
                startIndex = 1;
            }
            endIndex = (startIndex + pageLimit) - 1;
            if (jsnPager.TotalPageCount <= endIndex) {
                endIndex = jsnPager.TotalPageCount;
            }
            var previousSetCssClass = "no-set";
            var nextSetCssClass = "no-set";
            if (startIndex > 1) {
                previousSetCssClass = "";
            }
            if (endIndex < jsnPager.TotalPageCount) {
                nextSetCssClass = "";
            }
            $ulPager.append('<li class="' + jsnPager.PreviousPageCssClass + '"><button  data-index="-">Prev</button></li>');
            $ulPager.append('<li class="disabled ' + previousSetCssClass + '"></li>');
            for (var page = startIndex; page <= endIndex; page++) {
                var currentIndexCssClass = (page == jsnPager.PageIndex) ? 'active' : '';
                $ulPager.append('<li class="' + currentIndexCssClass + '"><button data-event="articlespagenumber-navigation-click" data-index="' + page + '">' + page + '</button></li>');
            }
            $ulPager.append('<li class="disabled ' + nextSetCssClass + '" ></li>');
            $ulPager.append('<li class="' + jsnPager.NextPageCssClass + '"><button  data-event="articlespagenumbernext-navigation-click" data-index="+">Next</button></li>');
            return $ulPager;
        }

        function getItemsCounterHtml(jsnPager, type) {
            var pageSize = type == "Articles" ? window.FRConfiguration.ArticlesV2PageSize : window.FRConfiguration.AuthorsV2PageSize;
            if (jsnPager.PageIndex == 1) {
                var pageSize = jsnPager.TotalItemCount < jsnPager.PageSize ? jsnPager.TotalItemCount : jsnPager.PageSize;
            }
            if ((jsnPager.PageIndex == jsnPager.TotalPageCount) && (jsnPager.TotalPageCount > 1)) {
                pageSize = jsnPager.TotalItemCount % pageSize                
            }

            
            var $itemsCounter = '<div class="pagination-items-counter"> ' + pageSize + ' of ' + jsnPager.TotalItemCount + ' ' + type  + '</div>';          
            return $itemsCounter;
           
        }

        function scrollToElement($cntrlToFocus) {
            $('html, body').animate({
                scrollTop: $cntrlToFocus.offset().top - 75
            }, 500);
        }
        return {
            getPagerHtml: getPagerHtml,
            showLoginPopUp: showLoginPopUp,
            getCurrentTab: getCurrentTab,
            scrollToElement: scrollToElement,
            getItemsCounterHtml: getItemsCounterHtml
        };
    })();
    var FRJournalResearchTopicHeader = (function () {
        $(function () {
            populateHeaderCounts();
        });
        var headerSummary = {};

        function populateHeaderCounts() {
            $.getJSON('/research-topics/' + window.FRResearchTopic.Id + '/summary').done(function (jsnCounts) {
                headerSummary = jsnCounts;
                renderHeaderCounts(jsnCounts);
            });
        }

        function bindImpactToolTip() {
            var $impactViews = $($divTopicHeader).find('.views-count').find('strong');
            $impactViews.tooltip({
                placement: 'bottom',
                delay: {
                    show: 400
                }
            });
        }

        function renderHeaderCounts(jsnCounts) {
            if (jsnCounts.IsArticlesCountVisible) {
                //$divPrimaryTabs.find('.articles .badge').text(jsnCounts.ArticlesCount);
                $divTopicHeader.find('#header-article-count').text(jsnCounts.ArticlesCount);
                $divTopicHeader.find('#header-article-number').text(jsnCounts.ArticlesCount);
                $divTabOverview.find('.overviewArticleCount').text(jsnCounts.ArticlesCount);
                $divTabArticles.find('#articles-count').text(jsnCounts.ArticlesCount);
                $divTopicHeader.find('#article-number-item').css("display", "flex");
            }
            
            if (jsnCounts.IsAuthorsCountVisible) {
                //$divPrimaryTabs.find('.authors .badge').text(jsnCounts.AuthorsCount);
                $divTopicHeader.find('#header-author-count').text(jsnCounts.AuthorsCount);
                $divTopicHeader.find('#header-author-number').text(jsnCounts.AuthorsCount);
                $divTabAuthors.find('#authors-count').text(jsnCounts.AuthorsCount);
                $divTopicHeader.find('#author-number-item').css("display", "flex");
            }
            
           
            if (jsnCounts.IsImpactViewsCountVisible) {
                $divTopicHeader.find('#header-impact-count').text(jsnCounts.ImpactViewsCountShortValue);
                $divTopicHeader.find('#header-suffix').text(jsnCounts.ImpactViewsCountSuffix);
                $divTopicHeader.find('#impact-number-item').css("display", "flex");
            }

            if (jsnCounts.IsImpactDownloadsCountVisible) {
                $divTopicHeader.find('#header-download-count').text(jsnCounts.ImpactDownloadsCountShortValue);
                $divTopicHeader.find('#header-download-suffix').text(jsnCounts.ImpactDownloadsCountSuffix);
                $divTopicHeader.find('#impact-download-item').css("display", "flex");
            }
            
        }

        return {
            summary: function () {
                return headerSummary;
            }
        };
    })();
    var FRJournalResearchTopicEditors = (function () {
        var $divWidgetEditors = $divPageContainer.find('.editor-list');
        $(function () {
            populateEditors();
        });

        function populateEditors() {
            $.getJSON(FRResearchTopicAPI.UrlTopicEditors).done(function (jsnEditors) {
                renderEditors(jsnEditors);
            }).fail(function () {
                throw new FRError({
                    className: 'FRJournalResearchTopicEditors',
                    methodName: 'populateEditors',
                    message: 'Failed to get the Editors'
                });
            }).always(function () {
                $divWidgetEditors.find('.loading-wrapper').remove();
            });
        }

        function renderEditors(jsnEditors) {
            if (!jsnEditors || !jsnEditors.Editors || !jsnEditors.Editors.length) {
                $divWidgetEditors.remove();
                return;
            }
            var htmlEditors = FRTemplate.bind('template-topic-editors', {
                editors: jsnEditors.Editors
            });
            if (!htmlEditors.length) {
                return;
            }
            var $divContainerEditors = $divWidgetEditors.find('.container-authors');
            $divContainerEditors.each(function () {
                var $this = $(this);
                $this.html(htmlEditors);
                $this.find('.teaser-links').last().addClass('last');
            });
            $(document).trigger('ui.load.images');
        }
    })();
    var FRJournalResearchTopicCoordinators = (function () {
        var $divWidgetCoordinators = $divPageContainer.find('.coordinator-list');
        $(function () {
            populateCoordinators();
        });

        function populateCoordinators() {
            $.getJSON(FRResearchTopicAPI.UrlTopicCoordinators).done(function (jsnCoordinators) {
                renderCoordinators(jsnCoordinators);
            }).fail(function () {
                throw new FRError({
                    className: 'FRJournalResearchTopicCoordinators',
                    methodName: 'populateCoordinators',
                    message: 'Failed to get the Coordinators'
                });
            }).always(function () {
                $divWidgetCoordinators.find('.loading-wrapper').remove();
            });
        }

        function renderCoordinators(jsnCoordinators) {
            if (!jsnCoordinators || !jsnCoordinators.Coordinators || !jsnCoordinators.Coordinators.length) {
                $divWidgetCoordinators.remove();
                return;
            }
            var htmlCoordinators = FRTemplate.bind('template-topic-coordinators', {
                coordinators: jsnCoordinators.Coordinators
            });
            if (!htmlCoordinators.length) {
                return;
            }
            var $divContainerCoordinators = $divWidgetCoordinators.find('.container-authors');
            $divContainerCoordinators.each(function () {
                var $this = $(this);
                $this.html(htmlCoordinators);
                $this.find('.teaser-links').last().addClass('last');
            });
            $(document).trigger('ui.load.images');
        }
    })();
    var FRJournalResearchTopicParticipatingJournals = (function () {
        var $divWidgetJournals = $divPageContainer.find('.participating-journal-list');
        $(function () {
            populateJournals();
        });

        function populateJournals() {
            $.getJSON(FRResearchTopicAPI.UrlTopicJournals).done(function (jsnJournals) {
                renderJournals(jsnJournals);
            }).fail(function () {
                throw new FRError({
                    className: 'FRJournalResearchTopicParticipatingJournals',
                    methodName: 'populateJournals',
                    message: 'Failed to get the Journals'
                });
            }).always(function () {
                $divWidgetJournals.find('.loading-wrapper').remove();
            });
        }

        function renderJournals(jsnJournals) {
            var researchtopicTerm = window.FRConfiguration.ResearchTopicTerminology
            if (!jsnJournals || !jsnJournals.ShowJournalsWidget) {
                $divWidgetJournals.remove();
                return;
            }
            var htmlJournals = FRTemplate.bind('template-topic-participating-journals', {
                journals: jsnJournals
            });
            if (!htmlJournals.length) {
                $divWidgetJournals.remove();
                return;
            }
            else {
                var $rightMenuHtml = '<section class="container-bordered journal-list muted">'+'<h2 class="bloc-title">Participating Journals</h2>' +
                    '<p class="intro-text">' + "Manuscripts can be submitted to this " + researchtopicTerm+" via the following journals:" + '</p >'
                    +'<div class="container-journals-list"></div>'+'</section>';

                $divWidgetJournals.append($rightMenuHtml);
            }
            var $divContainerJournals = $divWidgetJournals.find('.container-journals-list');
            $divContainerJournals.html(htmlJournals);
        }
    })();
    var FRJournalResearchTopicArticles = (function () {
        var pageSize = window.FRConfiguration.ArticlesV2PageSize;
        var $divArticlesPaged = $divTabArticles.find('.article-list');
        var $divArticlesRecent = $divTabOverview.find('.article-list');
        bindEvents();
        $(function () {
            populateRecentArticles();
        });

        function bindEvents() {
            $divPrimaryTabs.find('a[data-toggle="tab"].articles').on('show', function () {
                populateArticlesByIndex(1, pageSize, 'Default', false, false);
            });
            $divArticlesRecent.on('click', '.articles-all', function () {
                $divPrimaryTabs.find('a[href="research-topic-articles"]').closest('li').click();
                $divPrimaryTabs.find('.articles').tab('show');
                window.scrollTo(0, 0);
            });
            $divArticlesPaged.on('click', '.pagination li button', function () {
                manageArticlePagination($(this));
            });
            $divArticlesPaged.on('click', '.nav-sort li button', function () {
                $divArticlesPaged.find('.loading-wrapper').css('display', 'block');
                manageArticleSorting($(this));
            });
        }

        function populateArticlesByIndex(index, pageSize, sortBy, isRecent, isPagination) {
            var requestData = {
                index: index,
                sortBy: sortBy,
                pageSize: pageSize,
                isRecent: isRecent
            };
            $divArticlesPaged.find('.loading-wrapper').css('display', 'block');
                
            $.getJSON('/api/research-topics/' + window.FRResearchTopic.Id + '/articles', requestData).done(function (jsnArticleList) {
                renderArticlesByIndex(jsnArticleList, isPagination);
            }).fail(function () {
                throw new FRError({
                    className: 'FRJournalResearchTopic',
                    methodName: 'populateArticlesByIndex',
                    message: 'Failed to get the articles'
                });
            });
        }

        function renderArticlesByIndex(jsnArticleList, isPagination) {
            if (!jsnArticleList || !jsnArticleList.Articles || !jsnArticleList.Articles.length) {
                $divArticlesPaged.find('.loading-wrapper').css('display', 'none');
                $divArticlesPaged.find('#article-nav-sort').css('visibility', 'hidden');
                $divArticlesPaged.find('.container-message').text(jsnArticleList.HeaderInfoText);  
                $divArticlesPaged.find('.articles-wrapper').css('display', 'none');
                return;
            }

            var htmlArticleList = FRTemplate.bind('template-topic-articles', {
                articleList: jsnArticleList
            });
            if (!htmlArticleList.length) {
                return;
            }
            if (jsnArticleList.IsRecent) {
                $divArticlesRecent.find('.loading-wrapper').css('display', 'none');
                $divArticlesRecent.find('.articles-wrapper').html(htmlArticleList);
                $divArticlesRecent.find('.bottom-links').show();
                $divArticlesRecent.find('.articles-wrapper .teaser').first().addClass('first');
            } else {
                $divArticlesPaged.find('.loading-wrapper').css('display', 'none');
                $divArticlesPaged.find('.articles-wrapper').html(htmlArticleList);
                $divArticlesPaged.find('.nav-sort [data-sort]').parent().removeClass('active');
                $divArticlesPaged.find('.nav-sort [data-sort="' + jsnArticleList.Pager.SortBy + '"]').parent().addClass('active').show();
                
                $divArticlesPaged.find('.articles-wrapper .teaser').first().addClass('first');
                var htmlPager = FRJournalResearchTopicCommon.getPagerHtml(jsnArticleList.Pager);
                var itemsCounter = FRJournalResearchTopicCommon.getItemsCounterHtml(jsnArticleList.Pager, "Articles");
                $divArticlesPaged.find('.pagination').html(htmlPager).show();
                $divArticlesPaged.find('.pagination').append(itemsCounter);
            }
            $(document).trigger('ui.load.images');
            populateAltmetricBadges();
            if (isPagination) {
                FRJournalResearchTopicCommon.scrollToElement($divTabContent.find('#research-topic-articles'));
            }
        }

        function manageArticlePagination($this) {
            if ($this.parent('li').hasClass('active') || $this.parent('li').hasClass('disabled')) {
                return;
            }
            var indexToGo = $this.data('index');
            var sortBy = $divArticlesPaged.find('.nav-sort li.active button').data('sort');
            if (sortBy == undefined) {
                sortBy = 'Default';
            }
            var indexNow = $divArticlesPaged.find('.pagination li.active button').data('index');
            if (!isNaN(indexToGo)) { }
            if (indexToGo == '+') {
                indexToGo = indexNow + 1;
            }
            if (indexToGo == '-') {
                indexToGo = indexNow - 1;
            }
            if (!indexToGo || !sortBy.length) {
                return;
            }
            populateArticlesByIndex(indexToGo, pageSize, sortBy, false, true);
        }

        function manageArticleSorting($this) {
            var sortBy = $this.data('sort');
            if (!sortBy.length) {
                return;
            }
            if (sortBy == "views") {
                populateArticlesByIndex(1, pageSize, sortBy, false, false);
            }
            if (sortBy == "type") {
                populateArticlesByIndex(1, pageSize, sortBy, false, false);
            }
            if (sortBy == "date") {
                populateArticlesByIndex(1, pageSize, sortBy, false, false);
            }
        }

        function populateAltmetricBadges() {
            if (typeof window._altmetric_embed_init === "undefined") {
                return;
            }
            window._altmetric_embed_init();
        }

        function populateRecentArticles() {
            if (!$divArticlesRecent.length) {
                return;
            }
            populateArticlesByIndex(1, 3, 'Default', true, false);
        }
    })();
    var FRJournalResearchTopicAuthors = (function () {
        var pageSize = window.FRConfiguration.AuthorsV2PageSize;
        var $divAuthorsPaged = $divTabAuthors.find('.row-fluid');
        bindEvents();
        //$(function () {
        //    populateAuthors();
        //});

        function bindEvents() {
            $divPrimaryTabs.find('a[data-toggle="tab"].authors').on('show', function () {
                populateAuthorsByIndex(1, pageSize, false);
            });
            $divAuthorsPaged.on('click', '.pagination li button', function () {
                manageAuthorPagination($(this));
            });

        }

        function populateAuthorsByIndex(index, pageSize, isPagination) {
            var requestData = {
                index: index,
                pageSize: pageSize
            };
            
            $divAuthorsPaged.find('.loading-wrapper').css('display', 'block');

            $.getJSON('/api/research-topics/' + window.FRResearchTopic.Id + '/authors', requestData).done(function (jsnAuthorList) {
                $divAuthorsPaged.find('.container-authors').removeClass('disabled');
                renderAuthorsByIndex(jsnAuthorList, isPagination);

            }).fail(function () {
                throw new FRError({
                    className: 'FRJournalResearchTopic',
                    methodName: 'populateAuthorsByIndex',
                    message: 'Failed to get the authors'
                });
            });
        }
        function renderAuthorsByIndex(jsnAuthors, isPagination) {
            if (!jsnAuthors || !jsnAuthors.AuthorRows) {               
                $divAuthorsPaged.find('.loading-wrapper').css('display', 'none'); 
                $divAuthorsPaged.find('.container-message').show().find('p').text(jsnAuthors.InfoText);
                return;
            }
            var htmlAuthors = FRTemplate.bind('template-topic-authors', {
                jsnAuthors: jsnAuthors
            });
            if (!htmlAuthors.length) {
                return;
            }
            $divAuthorsPaged.find('.loading-wrapper').css('display', 'none');           
            $divTabAuthors.find('.container-authors').html(htmlAuthors);
            var htmlPager = FRJournalResearchTopicCommon.getPagerHtml(jsnAuthors.Pager);
            var itemsCounter = FRJournalResearchTopicCommon.getItemsCounterHtml(jsnAuthors.Pager, "Authors");
            $divAuthorsPaged.find('.pagination').html(htmlPager).show();
            $divAuthorsPaged.find('.pagination').append(itemsCounter);
            $(document).trigger('ui.load.images');
            //resetRowHeights();
            if (isPagination) {
                FRJournalResearchTopicCommon.scrollToElement($divTabContent.find('#research-topic-authors'));
            }
        }
        function manageAuthorPagination($this) {
            if ($this.parent('li').hasClass('active') || $this.parent('li').hasClass('disabled')) {
                return;
            }
            var indexToGo = $this.data('index');
            var indexNow = $divAuthorsPaged.find('.pagination li.active button').data('index');
            if (!isNaN(indexToGo)) { }
            if (indexToGo == '+') {
                indexToGo = indexNow + 1;
            }
            if (indexToGo == '-') {
                indexToGo = indexNow - 1;
            }
            if (!indexToGo) {
                return;
            }
            populateAuthorsByIndex(indexToGo, pageSize, true);
        }

        function resetRowHeights() {
            $divTabAuthors.find('.container-authors .row-fluid').each(function (i, authorRow) {
                var tallestBoxHeight = 0;
                var $divAuthorBoxesInCurrentRow = $(authorRow).find('.teaser-container .container-bordered .teaser');
                $divAuthorBoxesInCurrentRow.each(function (j, authorBox) {
                    var currentAuthorBoxHeight = $(authorBox).height();
                    if (currentAuthorBoxHeight > tallestBoxHeight) {
                        tallestBoxHeight = currentAuthorBoxHeight;
                    }
                });
                $divAuthorBoxesInCurrentRow.height(tallestBoxHeight);
            });
        }
    })();
    var FRJournalResearchTopicJournals = (function () {
        var body = $('body');
        var $modalContainer = $('.modal-container');
        var $researchTopicsheader = $('#research-topics-header');
        $(function () {
            bindEvents();
        });

        function bindEvents() {
            $modalContainer.on('click', '.btn-close', function () {
                closeModal();
            });
            $researchTopicsheader.on('click', '.btn-manuscript-crosslisted', function () {
                var submissionType = "manuscript";
                populateResearchTopicJournals(submissionType);
            });
           
        }

        function populateResearchTopicJournals(submissionType) {
            $.getJSON('/research-topics/' + window.FRResearchTopic.Id + '/journals/' + submissionType).done(function (jsnJournals) {
                manageJournalSubmission(jsnJournals);
            }).fail(function () {
                throw new FRError({
                    className: 'FRJournalResearchTopicJournals',
                    methodName: 'populateResearchTopicJournals',
                    message: 'Failed to get the journals'
                });
            });
        }

        function disableButton(button) {
            button.addClass("Link--disabled");
            button.attr("aria-disabled", "true");
            button.removeAttr("href");
        }

        function enableButton(button) {
            button.removeClass("Link--disabled");
            button.removeAttr("aria-disabled");
        }

        $modalContainer.on('change', 'input[name="submit-idea"]', function (e) {
            var itemSelectedValue = $("input[name='submit-idea']:checked").val();
            var submitManuscriptLink = $("#submit-your-manuscript-link"),
                submitAbstractLink = $("#submit-your-abstract-link");
            if (itemSelectedValue) {
                if (submitManuscriptLink.hasClass("Link--disabled")) {
                    enableButton(submitManuscriptLink)
                    enableButton(submitAbstractLink)
                }
                submitManuscriptLink.attr("href", itemSelectedValue.toString());

                var url = new URL(itemSelectedValue);
                var searchParams = url.searchParams;
                // CHECK THIS, FROM WHAT I HAVE SEEN IN THE API THE VALUE 3 CORRESPONDS TO SUBMIT WITH ABSTRACT
                searchParams.set('st', 3);
                url.search = searchParams.toString();
                submitAbstractLink.attr("href", url.toString());
            } else if (!submitManuscriptLink.hasClass("Link--disabled")) {
                disableButton(submitManuscriptLink);
                disableButton(submitAbstractLink);
            }
        });

        function manageJournalSubmission(journals) {
            if (!journals) return;
            var journalCount = getJournalsCount(journals);
            // BEGIN TODO UXD-1320: CHANGED THIS CODE, NOW ALWAYS THE MODAL WILL BE OPENED, AND THERE THE USER CAN SUBMIT AN ABSTRATC OR A MANUSCRIPT.
            if (journalCount <= 0) {
                return;
            } else {
                var submissionManuscriptPath = '',
                    submissionAbstractPath = '';
                if (journalCount === 1) {
                    if (journals.SpecialtyJournals && journals.SpecialtyJournals.length) {
                        submissionManuscriptPath = journals.SpecialtyJournals[0].SubmissionUrl;
                    } else if (journals.FieldJournals && journals.FieldJournals.length) {
                        submissionManuscriptPath = journals.FieldJournals[0].Sections[0].SubmissionUrl;
                    }
                    if (submissionManuscriptPath) {
                        var url = new URL(submissionManuscriptPath);
                        var searchParams = url.searchParams;
                        searchParams.set('st', 3);
                        url.search = searchParams.toString();
                        submissionAbstractPath = url.toString()
                    }
                }
                var journalHtml = FRTemplate.bind('template-topic-journals', {
                    journals: journals,
                    submissionManuscriptPath: submissionManuscriptPath,
                    submissionAbstractPath: submissionAbstractPath
                });
                $('.journal-container').html(journalHtml);
                $modalContainer.fadeIn('500', function () { // Animation complete
                    body.addClass('body-locked');
                    $('.modal-backdrop').show();
                    $modalContainer.addClass('dp-block');
                });
            }
            
            // END TODO UXD-1320: CHANGED THIS CODE, NOW ALWAYS THE MODAL WILL BE OPENED, AND THERE THE USER CAN SUBMIT AN ABSTRATC OR A MANUSCRIPT.
        };

        function getJournalsCount(journals) {
            var journalCount = 0;
            if (journals.FieldJournals && journals.FieldJournals.length) {
                $(journals.FieldJournals).each(function (i, field) {
                    if (field && field.Sections && field.Sections.length) {
                        journalCount = journalCount + field.Sections.length;
                    }
                });
            }
            if (journals.SpecialtyJournals && journals.SpecialtyJournals.length) {
                journalCount = journalCount + journals.SpecialtyJournals.length;
            }
            return journalCount;
        }

        function closeModal() {
            $('.modal-backdrop').hide();
            body.removeClass('body-locked');
            $modalContainer.removeClass('dp-block');
        }
    })();
    var FRJournalResearchTopicSponsorshipDetails = (function () {
        var $divWidgetSponsorship = $divPageContainer.find('.sponsorship-list');
        $(function () {
            populateSponsorshipDetails();
        });

        function populateSponsorshipDetails() {
            $.getJSON(FRResearchTopicAPI.UrlTopicSponsorships).done(function (jsnSponsorships) {
                renderSponsorships(jsnSponsorships);
            }).fail(function () {
                throw new FRError({
                    className: 'FRJournalResearchTopicSponsorshipDetails',
                    methodName: 'populateSponsorshipDetails',
                    message: 'Failed to get the Sponsorship details'
                });
            }).always(function () { });
        }

        function renderSponsorships(jsnSponsorships) {
            if (!jsnSponsorships || !jsnSponsorships.length) {
                $divWidgetSponsorship.remove();
                return;
            }

            

            var htmlSponsorships = FRTemplate.bind('template-topic-sponsorship_details', {
                sponsorships: jsnSponsorships
            });
            if (!htmlSponsorships.trim().length) {
                $divWidgetSponsorship.remove();
                return;
            }
            else {
                var $sponsorshipHtml = '<section class="container-bordered about-text sponsorship-lists">' + '<h2 class="bloc-title">'+'Sponsorship'+'</h2 >' +
                    '<div class="container-sponsorship">'+
                     '</div>'+'</section>';

                $divWidgetSponsorship.append($sponsorshipHtml);
                var $divContainerSponsorship = $divWidgetSponsorship.find('.container-sponsorship');
                
            }
            $divContainerSponsorship.html(htmlSponsorships);
        }
    })();
    var FRResearchTopicAPI = (function () {
        var apiUrlPrefix = '/api/research-topics/';
        return {
            UrlTopicEditors: (apiUrlPrefix + window.FRResearchTopic.Id + '/topiceditors'),
            UrlTopicCoordinators: (apiUrlPrefix + window.FRResearchTopic.Id + '/topiccoordinators'),
            UrlTopicJournals: (apiUrlPrefix + window.FRResearchTopic.Id + '/journals'),
            UrlTopicSponsorships: (apiUrlPrefix + window.FRResearchTopic.Id + '/sponsorshipdetails')

        };
    })();

})();;


var ResearchTopicImpact = (function () {
    var $tabImpact = $(".tab-impact");
    var $liPrimaryTabs = $('#primaryTabs').find('li');
    var $divPageContainer = $('.page-container');
    var $divTabContent = $divPageContainer.find('.tab-content');
    var $divTabImpact = $divTabContent.find('#research-topic-impact');
    var charttype = "timeline"; //default value
    var renderMap = false;
    var isImpactVisited = false;
    var selectedValue = null;
    var impactData = {
        views: {},
        demographics: {}
    };
    $(function () {
        bindEvents();
        renderToolTip();
        bindGoogleAnalyticsTracking();
    });

    function bindEvents() {
        $tabImpact.on("click", "#views-timeline-button", function () {
            charttype = "timeline";
            renderTimelineChartEvent();
        });
        $tabImpact.on("click", "#views-bar-button", function () {
            charttype = "bar";
            renderBarChartEvent();
        });
        $("#research-topics-section").on(
            "click",
            ".tab-impact .topic-impact-tabs.nav-tabs > li > a",
            function (e) {
                switch ($(e.target).data("tabType")) {
                    case "views":
                        break;
                    case "demographics":
                        renderDemographicsTab();
                        break;
                }
            });
        // selects an element from dropdown and change graph period
        $tabImpact.on("click", ".dropdown-menu li", function (event) {
            renderViewsGraph(event);
        });
        $(window).on("hashchange", function () {
            manageImpactTabNavigation();
        });
        $(window).on("load", function () {
            manageImpactTabNavigation();
        });
        $liPrimaryTabs.on('click', function () {
            manageImpactTabNavigation();
        });
    }

    async function populateImpactViews() {
        await $.getJSON('/research-topics/impact/getimpactviews?topicId=' + FRResearchTopic.Id).done(function (jsnData) {
            if (jsnData != null && jsnData.IsVisible == true) {
                impactData.views = jsnData;
                populateViewsTabCount();
                highlightTimeLineButton();
                $.each(jsnData.TimePeriodOptions, function (index, timePeriod) {
                    $("#PeriodDropTGK").append(
                        '<li id="' +
                        timePeriod +
                        '" class="' +
                        timePeriod +
                        '"><a data-event = "impact' + timePeriod.toLowerCase().replace(/\s+/g, '') + '-details-click">' +
                        timePeriod +
                        "</a></li>"
                    );
                });
            } else {
                $tabImpact.find(".loading-wrapper").hide();
                $tabImpact.find(".impact-topic-tabs").show();
                var emptyMessage = "<p class='no-records'>No records found</p>";
                $tabImpact.find("#views-tab").html(emptyMessage);
            }
        });
        return true;
    }

    async function populateDemographics() {
        await $.getJSON('/research-topics/impact/getimpactdemographics?topicId=' + FRResearchTopic.Id).done(function (jsnData) {
            if (jsnData != null && jsnData.IsVisible) {
                impactData.demographics = jsnData;
            } else {
                var emptyMessage = "<p class='no-records'>No records found</p>";
                $tabImpact.find("#demographics-tab").html(emptyMessage);
            }
        });
        return true;
    }

    function showTimeGranularity(period, impactSummary) {
        if (impactSummary != null) {
            var selectedPeriod = $.grep(impactSummary, function (v) {
                return v.TimePeriod === period;
            });
            if (selectedPeriod != null) {
                selectedPeriod = selectedPeriod[0];
                $(".impact-title").text(period);
                $(".timeperiod")
                    .find(".total-views")
                    .text(selectedPeriod.TotalViewsCount);
                $(".timeperiod")
                    .find(".article-views")
                    .text(selectedPeriod.ArticleViewsCount);
                $(".timeperiod")
                    .find(".downloads")
                    .text(selectedPeriod.ArticleDownloadsCount);
                $(".timeperiod")
                    .find(".topic-views")
                    .text(selectedPeriod.TopicViewsCount);
                $divTabImpact.find('#impact-views-count').text(selectedPeriod.TotalViewsCount);
            }
        }
    }

    function populateViewsTabCount() {
        if (impactData.views != null && impactData.views.TotalViews) {
            $tabImpact
                .find(".nav-tabs .total-views")
                .text(impactData.views.TotalViews);
        } else {
            $tabImpact.find(".nav-tabs .total-views").addClass("hide");
        }
    }

    // BEGIN TODO UXD-1466: OPENING DROPDOWN BUG ON MOBILE FIX
    $(function () {
        $('.dropdown-toggle').on('touchstart', function (e) {
            console.log("touchstart");
            e.stopPropagation();
        });
    });
    // END TODO UXD-1466: OPENING DROPDOWN BUG ON MOBILE FIX

    function renderViewsTab() {
        if (impactData.views.IsVisible == true) {
            $("#views-bar-chart").hide();
            $("#views-timeline-chart").show();
            if (impactData.views.IsPMCDataAvailable) {
                $tabImpact.find(".impact-tab-footer-pmc").show();
            }
            populateImpactViewDefaultOption();
            renderDefaultTimeLine();
        } else {
            var emptyMessage = "<p class='no-records'>No records found</p>";
            $tabImpact.find("#views-tab").html(emptyMessage);
        }
    }

    function populateImpactViewDefaultOption() {
        showTimeGranularity(
            impactData.views.DefaultViewScaleOption,
            impactData.views.ImpactSummary
        );
    }

    function renderDemographicsTab() {
        renderGoogleMap();
        demographicsTopCountries();
        demographicsTopSites();
        demographicsDomain();
        demographicsField();
        demographicsSpecialty();
        demographicsIndustry();
        demographicsEducation();
        demographicsPosition();
        demographicsGender();
    }

    function renderViewsGraph(event) {
        var $target = $(event.currentTarget);
        var type = $target.attr("id");
        if (charttype == "timeline") {
            renderTimeLineChart(type, impactData.views.ImpactSummary);
        }
        if (charttype == "bar") {
            renderBarChart(type, impactData.views.ImpactSummary);
        }
        $target
            .closest(".btn-group")
            .find('[data-bind="label"]')
            .text($target.text())
            .end()
            .children(".dropdown-toggle")
            .dropdown("toggle");
    }

    function renderTimeLineChart(period, ImpactSummary) {
        if (ImpactSummary == null) {
            $(".chart-container").hide();
            $(".views-empty-message").show();
        } else {
            $(".chart-container").show();
            $(".views-empty-message").hide();
            viewsTimeline(period, impactData.views.ImpactSummary);
            showTimeGranularity(period, impactData.views.ImpactSummary);
        }
    }

    function renderTimelineChartEvent() {
        var timePeriod = $("#Period").text();
        $("#views-bar-chart").hide();
        $("#views-timeline-chart").show();
        $("#views-bar-button").removeClass("active");
        $("#views-timeline-button").addClass("active");
        renderTimeLineChart(timePeriod, impactData.views.ImpactSummary);
    }

    function renderBarChart(period, ImpactSummary) {
        if (ImpactSummary == null) {
            $(".chart-container").hide();
            $(".views-empty-message").show();
        } else {
            $(".chart-container").show();
            $(".views-empty-message").hide();
            viewsBarChart(period, impactData.views.ImpactSummary);
            showTimeGranularity(period, impactData.views.ImpactSummary);
        }
    }

    function renderBarChartEvent() {
        var timePeriod = $("#Period").text();
        $("#views-timeline-chart").hide();
        $("#views-bar-chart").show();
        $("#views-timeline-button").removeClass("active");
        $("#views-bar-button").addClass("active");
        renderBarChart(timePeriod, impactData.views.ImpactSummary);
    }

    function highlightTimeLineButton() {
        $("#views-bar-chart").hide();
        $("#views-timeline-chart").show();
        $("#views-bar-button").removeClass("active");
        $("#views-timeline-button").addClass("active");
    }
    //VIEWS bar chart
    function viewsBarChart(period, impactSummary) {
        if (impactSummary == null) return;
        var selectedPeriod = $.grep(impactSummary, function (v) {
            return v.TimePeriod === period;
        });
        selectedPeriod = selectedPeriod[0];
        $("#views-bar-chart").highcharts({
            credits: {
                enabled: false
            },
            chart: {
                type: "column",
                style: {
                    fontFamily: '"Open Sans", "Helvetica Neue", Helvetica, Arial',
                    fontSize: 14
                },
                marginBottom: 80,
                marginLeft: 47
            },
            title: {
                text: null
            },
            xAxis: {
                gridLineColor: "#e0e0e0",
                gridLineWidth: 1,
                lineColor: "#e0e0e0",
                tickColor: "#e0e0e0",
                categories: selectedPeriod.Categories
            },
            yAxis: {
                gridLineColor: "#e0e0e0",
                gridLineWidth: 1,
                lineColor: "#e0e0e0",
                min: 0,
                title: {
                    text: "Views",
                    margin: 2
                },
                labels: {
                    x: -5
                }
            },
            tooltip: {
                headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
                pointFormat:
                    '<tr><td style="color:{series.color};padding:0">{series.name}:&nbsp;</td>' +
                    '<td style="padding:0"><b>{point.y}</b></td></tr>',
                footerFormat: "</table>",
                shared: true,
                useHTML: true
            },
            plotOptions: {
                series: {
                    stacking: "normal"
                }
            },
            series: [
                {
                    name: "Article Views",
                    color: "#dccd00",
                    data: selectedPeriod.ArticleViewsData
                },
                {
                    name: "Downloads",
                    color: "#7d7900",
                    data: selectedPeriod.DownloadsData
                },
                {
                    name: "Topic Views",
                    color: "#000000",
                    data: selectedPeriod.TopicViewsData
                }
            ]
        });
    }
    //VIEWS TimeLine chart
    function viewsTimeline(period, impactSummary) {
        var selectedPeriod = $.grep(impactSummary, function (v) {
            return v.TimePeriod === period;
        });
        selectedPeriod = selectedPeriod[0];
        var currentYear = "";
        var isMonthCombined = false;
        $("#views-timeline-chart").highcharts({
            credits: {
                enabled: false
            },
            chart: {
                type: "spline",
                style: {
                    fontFamily: '"Open Sans", "Helvetica Neue", Helvetica, Arial',
                    fontSize: 14
                },
                marginLeft: 47
            },
            title: {
                text: null
            },
            xAxis: {
                gridLineColor: "#e0e0e0",
                gridLineWidth: 1,
                lineColor: "#e0e0e0",
                tickColor: "#e0e0e0",
                categories: selectedPeriod.Categories,
                labels: {
                    formatter: function () {
                        if (this.isFirst) {
                            isMonthCombined = this.value.indexOf("-") > 0;
                        }
                        if (isMonthCombined) {
                            var year = this.value.slice(-4);
                            if (currentYear != year) {
                                currentYear = year;
                                return currentYear;
                            }
                            return "";
                        }
                        if (this.isLast) {
                            currentYear = "";
                        }
                        return this.value;
                    }
                }
            },
            yAxis: {
                gridLineColor: "#e0e0e0",
                gridLineWidth: 1,
                lineColor: "#e0e0e0",
                title: {
                    text: "Views",
                    margin: 2
                },
                min: 0,
                labels: {
                    x: -5
                }
            },
            plotOptions: {
                series: {
                    allowPointSelect: true
                }
            },
            series: [
                {
                    name: FRResearchTopic.SinceBeginingTotalViewText,
                    lineWidth: 6,
                    color: "#f29400",
                    marker: {
                        symbol: "circle",
                        fillColor: "#FFFFFF",
                        radius: 7,
                        lineWidth: 5,
                        lineColor: null // inherit from series
                    },
                    data: selectedPeriod.SummedViewsData
                },
                {
                    name: FRResearchTopic.SinceBeginingArticleViewText,
                    visible: false,
                    lineWidth: 6,
                    color: "#7d7900",
                    marker: {
                        symbol: "circle",
                        fillColor: "#FFFFFF",
                        radius: 7,
                        lineWidth: 5,
                        lineColor: null // inherit from series
                    },
                    // Define the data points. All series have a dummy year
                    // of 1970/71 in order to be compared on the same x axis. Note
                    // that in JavaScript, months start at 0 for January, 1 for February etc.
                    data: selectedPeriod.ArticleViewsData
                },
                {
                    name: "Article Downloads",
                    visible: false,
                    lineWidth: 6,
                    color: "#eccc00",
                    marker: {
                        symbol: "circle",
                        fillColor: "#FFFFFF",
                        radius: 7,
                        lineWidth: 5,
                        lineColor: null // inherit from series
                    },
                    data: selectedPeriod.DownloadsData
                },
                {
                    name: "Topic Views",
                    visible: false,
                    lineWidth: 6,
                    color: "#000000",
                    marker: {
                        symbol: "circle",
                        fillColor: "#FFFFFF",
                        radius: 7,
                        lineWidth: 5,
                        lineColor: null // inherit from series
                    },
                    data: selectedPeriod.TopicViewsData
                }
            ]
        });
        $('text:contains("Highcharts.com")').hide();
    }

    function renderDefaultTimeLine() {
        renderTimeLineChart(impactData.views.DefaultViewScaleOption, impactData);
        populateBeginingTextInDropDown();
    }

    function populateBeginingTextInDropDown(target) {
        var $dropDownMenu = $(".dropdown-menu");
        $dropDownTarget = $dropDownMenu.find(
            "." + impactData.views.DefaultViewScaleOption
        );
        $(".btn-group")
            .find('[data-bind="label"]')
            .text(impactData.views.DefaultViewScaleOption)
            .end();
    }

    function renderGoogleMap() {
        $(".tab-content.topic-impact-tabs #demographics-tab").addClass("active");
        var center = new google.maps.LatLng(20.0, 5.0);
        var map = new google.maps.Map(document.getElementById("map"), {
            zoom: 2,
            center: center,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            scrollwheel: false
        });
        var styles = [
            {
                featureType: "water",
                stylers: [
                    {
                        color: "#f5f8fc"
                    }
                ]
            },
            {
                featureType: "landscape.natural",
                stylers: [
                    {
                        color: "#deddbf"
                    }
                ]
            },
            {
                featureType: "poi.park",
                elementType: "geometry",
                stylers: [
                    {
                        color: "#cac998"
                    }
                ]
            },
            {}
        ];
        map.setOptions({
            styles: styles
        });
        var markers = [];
        if (
            impactData.demographics.OriginLocations != null &&
            impactData.demographics.OriginLocations.IsVisible
        ) {
            $.each(
                impactData.demographics.OriginLocations.DemographicsDetails,
                function (index, value) {
                    var latLng = new google.maps.LatLng(value.Latitude, value.Longitude);
                    var gmarker = new MarkerWithLabel({
                        position: latLng,
                        draggable: false,
                        icon: "/areas/faceliftedV2-research-topics/Content/Images/frontiers/common/impact/marker2.png",
                        labelContent: value.VisitCount,
                        labelAnchor: new google.maps.Point(16, 33),
                        labelClass: "labels", // the CSS class for the label
                        labelInBackground: false,
                        title: this.City + " (" + this.VisitCount + " visits)"
                    });
                    google.maps.event.addListener(gmarker, "click", function () {
                        map.panTo(gmarker.getPosition());
                    });
                    markers.push(gmarker);
                }
            );
        }
        //set style options for marker clusters (these are the default styles)
        mcOptions = {
            styles: [
                {
                    height: 53,
                    url: "/areas/faceliftedV2-research-topics/Content/Images/frontiers/common/impact/m1.png",
                    width: 53
                },
                {
                    height: 56,
                    url: "/areas/faceliftedV2-research-topics/Content/Images/frontiers/common/impact/m2.png",
                    width: 56
                },
                {
                    height: 66,
                    url: "/areas/faceliftedV2-research-topics/Content/Images/frontiers/common/impact/m3.png",
                    width: 66
                },
                {
                    height: 78,
                    url: "/areas/faceliftedV2-research-topics/Content/Images/frontiers/common/impact/m4.png",
                    width: 78
                },
                {
                    height: 90,
                    url: "/areas/faceliftedV2-research-topics/Content/Images/frontiers/common/impact/m5.png",
                    width: 90
                }
            ]
        };
        //init clusterer with your options
        var markerCluster = new MarkerClusterer(map, markers, mcOptions);
        markerCluster.setCalculator(function (markers) {
            var total = 0;
            for (var i = 0; i < markers.length; i++) {
                total += parseInt(markers[i].labelContent);
            }
            var text = total;
            var index = 1;
            if (total > 500 && total <= 1000) {
                text = total;
                index = 2;
            } else if (total > 1000 && total < 1000000) {
                text = Math.floor(total / 1000);
                if (text >= 1 && text < 5) {
                    index = 3;
                } else if (text >= 5 && text < 10) {
                    index = 4;
                } else if (text >= 10) {
                    index = 5;
                }
                text = text + "K+";
            } else if (total >= 1000000 && total < 1000000000) {
                text = Math.floor(total / 1000000) + "M+";
                index = 5;
            } else if (total >= 1000000000) {
                text = "1T+";
                index = 5;
            }
            return {
                text: text,
                index: index
            };
        });
        google.maps.event.addListenerOnce(map, "idle", function () {
            $("#map-container").find("img.map-loading").hide();
        });
        //var markerCluster = new MarkerClusterer(map, markers);
    }

    function demographicsTopCountries() {
        if (
            impactData.demographics.TopViewingCountries != null &&
            impactData.demographics.TopViewingCountries.IsVisible
        ) {
            var xAxisData = [];
            var yAxisData = [];
            $.each(
                impactData.demographics.TopViewingCountries.DemographicsDetails,
                function (index, value) {
                    xAxisData.push(value.XValue);
                    yAxisData.push({
                        y: value.YValue
                    });
                }
            );
            $("#demographics-top-countries").highcharts({
                chart: {
                    type: "bar",
                    // width: 370, this property must be removed in order to make responsive the chart
                    height: 300,
                    marginLeft: 0,
                    style: {
                        fontFamily: '"Open Sans", "Helvetica Neue", Helvetica, Arial',
                        fontSize: 14
                    }
                },
                title: {
                    text: null
                },
                xAxis: {
                    categories: xAxisData,
                    tickWidth: 0,
                    title: {
                        text: null
                    },
                    labels: {
                        align: "left",
                        x: 0,
                        y: -18,
                        style: {
                            whiteSpace: "nowrap",
                            color: "black"
                        }
                    }
                },
                yAxis: {
                    min: 0,
                    title: {
                        enabled: false
                    },
                    labels: {
                        overflow: "justify"
                    },
                    gridLineColor: "#e0e0e0"
                },
                plotOptions: {
                    bar: {
                        dataLabels: {
                            enabled: true,
                            style: {
                                color: "#000000",
                                fontWeight: "700",
                                fontSize: "16px",
                                lineHeight: "30px"
                            },
                            y: 1
                        },
                        pointWidth: 25
                    }
                },
                legend: {
                    enabled: false
                },
                credits: {
                    enabled: false
                },
                series: [
                    {
                        name: "Views",
                        color: "#7d7900",
                        data: yAxisData
                    }
                ]
            });
        } else {
            var emptyMessage = "<p class='empty-message'>No records found</p>";
            $("#demographics-top-countries").html(emptyMessage);
        }
    }

    function demographicsDomain() {
        if (
            impactData.demographics.DomainDemographics != null &&
            impactData.demographics.DomainDemographics.IsVisible
        ) {
            var tableTemplate = "";
            if (impactData.demographics.DomainDemographics.IsOtherVisible) {
                tableTemplate = [
                    "<table>",
                    "<tr>",
                    '<th style="padding-bottom: 5px;">{{otherName}}</th>',
                    '<th style="text-align: right; padding-bottom: 10px;"><b>{{otherCount}}</b></th>',
                    "</tr>",
                    "{{fieldContents}}",
                    "</table>"
                ].join("");
                var content = [
                    "<tr>",
                    "<td>{{fieldName}}</td>",
                    '<td style="text-align: right;"><b>{{viewCount}}</b></td>',
                    "</tr>"
                ].join("");
                var fieldContents = "";
                $.each(
                    impactData.demographics.DomainDemographics.OtherDetails,
                    function (index, value) {
                        fieldContents += content
                            .replace("{{fieldName}}", value.XValue)
                            .replace("{{viewCount}}", value.YValue);
                    }
                );
                tableTemplate = tableTemplate
                    .replace(
                        "{{otherName}}",
                        impactData.demographics.DomainDemographics.Other.XValue
                    )
                    .replace(
                        "{{otherCount}}",
                        impactData.demographics.DomainDemographics.Other.YValue
                    );
                tableTemplate = tableTemplate.replace(
                    "{{fieldContents}}",
                    fieldContents
                );
            }
            var domainData = [];
            $.each(
                impactData.demographics.DomainDemographics.DemographicsDetails,
                function (index, value) {
                    domainData.push({
                        name: value.XValue,
                        y: value.YValue,
                        color: impactData.demographics.DomainDemographics.ColorCodes[index]
                    });
                }
            );
            $("#demographics-domain").highcharts({
                credits: {
                    enabled: false
                },
                chart: {
                    type: "pie",
                    width: 250,
                    height: 310,
                    style: {
                        fontFamily: '"Open Sans", "Helvetica Neue", Helvetica, Arial',
                        fontSize: 14
                    }
                },
                title: {
                    text: null
                },
                legend: {
                    layout: "vertical",
                    itemMarginTop: 2,
                    itemMarginBottom: 2,
                    useHTML: true,
                    labelFormatter: function () {
                        return (
                            '<span style="font-weight: 600;" title="' +
                            this.name +
                            '">' +
                            trimLegendName(this.name) +
                            "</span>" +
                            " " +
                            '<b style="font-weight: 800; font-size: 14;">' +
                            this.y +
                            "</b>"
                        );
                    }
                },
                tooltip: {
                    useHTML: true,
                    borderWidth: 0,
                    shadow: false,
                    backgroundColor: "transparent",
                    formatter: function () {
                        if (
                            this.point.name == "Other" &&
                            impactData.demographics.DomainDemographics.IsOtherVisible
                        ) {
                            return (
                                '<div class="t-container" style="border: 1px solid' +
                                this.point.color +
                                ';position:absolute;">' +
                                tableTemplate +
                                "</div>"
                            );
                        } else {
                            return (
                                '<div class="t-container" style="border: 1px solid' +
                                this.point.color +
                                '"><div class="t-simple">' +
                                this.point.name +
                                "<strong> " +
                                this.point.y +
                                "</strong></div></div>"
                            );
                        }
                    },
                    style: {
                        zIndex: 1000
                    }
                },
                plotOptions: {
                    pie: {
                        center: [96, 60],
                        size: 160,
                        innerSize: 102,
                        point: {
                            events: {
                                legendItemClick: function () {
                                    this.mouseOver();
                                    chart.tooltip.refresh(this);
                                    return false;
                                }
                            }
                        },
                        allowPointSelect: true,
                        cursor: "pointer",
                        dataLabels: {
                            enabled: false
                        },
                        showInLegend: true
                    }
                },
                series: [
                    {
                        data: domainData
                    }
                ]
            });
        } else {
            var emptyMessage = "<p class='empty-message'>No records found</p>";
            $("#demographics-domain").html(emptyMessage);
        }
    }

    function demographicsField() {
        if (
            impactData.demographics.FieldDemographics != null &&
            impactData.demographics.FieldDemographics.IsVisible
        ) {
            var tableTemplate = "";
            if (impactData.demographics.FieldDemographics.IsOtherVisible) {
                tableTemplate = [
                    "<table>",
                    "<tr>",
                    '<th style="padding-bottom: 5px;">{{otherName}}</th>',
                    '<th style="text-align: right; padding-bottom: 10px;"><b>{{otherCount}}</b></th>',
                    "</tr>",
                    "{{fieldContents}}",
                    "</table>"
                ].join("");
                var content = [
                    "<tr>",
                    "<td>{{fieldName}}</td>",
                    '<td style="text-align: right;"><b>{{viewCount}}</b></td>',
                    "</tr>"
                ].join("");
                var fieldContents = "";
                $.each(
                    impactData.demographics.FieldDemographics.OtherDetails,
                    function (index, value) {
                        fieldContents += content
                            .replace("{{fieldName}}", value.XValue)
                            .replace("{{viewCount}}", value.YValue);
                    }
                );
                tableTemplate = tableTemplate
                    .replace(
                        "{{otherName}}",
                        impactData.demographics.FieldDemographics.Other.XValue
                    )
                    .replace(
                        "{{otherCount}}",
                        impactData.demographics.FieldDemographics.Other.YValue
                    );
                tableTemplate = tableTemplate.replace(
                    "{{fieldContents}}",
                    fieldContents
                );
            }
            var fieldData = [];
            $.each(
                impactData.demographics.FieldDemographics.DemographicsDetails,
                function (index, value) {
                    fieldData.push({
                        name: value.XValue,
                        y: value.YValue,
                        color: impactData.demographics.FieldDemographics.ColorCodes[index]
                    });
                }
            );
            $("#demographics-field").highcharts({
                credits: {
                    enabled: false
                },
                chart: {
                    type: "pie",
                    width: 250,
                    height: 310,
                    style: {
                        fontFamily: '"Open Sans", "Helvetica Neue", Helvetica, Arial',
                        fontSize: 14
                    }
                },
                title: {
                    text: null
                },
                legend: {
                    layout: "vertical",
                    itemMarginTop: 2,
                    itemMarginBottom: 2,
                    useHTML: true,
                    labelFormatter: function () {
                        return (
                            '<span style="font-weight: 600;" title="' +
                            this.name +
                            '">' +
                            trimLegendName(this.name) +
                            "</span>" +
                            " " +
                            '<b style="font-weight: 800; font-size: 14;">' +
                            this.y +
                            "</b>"
                        );
                    }
                },
                tooltip: {
                    useHTML: true,
                    borderWidth: 0,
                    shadow: false,
                    backgroundColor: "transparent",
                    formatter: function () {
                        if (
                            this.point.name == "Other" &&
                            impactData.demographics.FieldDemographics.IsOtherVisible
                        ) {
                            return (
                                '<div class="t-container" style="border: 1px solid' +
                                this.point.color +
                                ';position:absolute;">' +
                                tableTemplate +
                                "</div>"
                            );
                        } else {
                            return (
                                '<div class="t-container" style="border: 1px solid' +
                                this.point.color +
                                '"><div class="t-simple">' +
                                this.point.name +
                                "<strong> " +
                                this.point.y +
                                "</strong></div></div>"
                            );
                        }
                    },
                    style: {
                        zIndex: 1000
                    }
                },
                plotOptions: {
                    pie: {
                        center: [96, 60],
                        size: 160,
                        innerSize: 102,
                        point: {
                            events: {
                                legendItemClick: function () {
                                    // some code here to achieve my goal
                                    this.mouseOver();
                                    chart.tooltip.refresh(this);
                                    return false; // <== returning false will cancel the default action
                                }
                            }
                        },
                        allowPointSelect: true,
                        cursor: "pointer",
                        dataLabels: {
                            enabled: false
                        },
                        showInLegend: true
                    }
                },
                series: [
                    {
                        data: fieldData
                    }
                ]
            });
        } else {
            var emptyMessage = "<p class='empty-message'>No records found</p>";
            $("#demographics-field").html(emptyMessage);
        }
    }

    function demographicsSpecialty() {
        if (
            impactData.demographics.SpecialtyDemographics != null &&
            impactData.demographics.SpecialtyDemographics.IsVisible
        ) {
            var tableTemplate = "";
            if (impactData.demographics.SpecialtyDemographics.IsOtherVisible) {
                tableTemplate = [
                    "<table>",
                    "<tr>",
                    '<th style="padding-bottom: 5px;">{{otherName}}</th>',
                    '<th style="text-align: right; padding-bottom: 10px;"><b>{{otherCount}}</b></th>',
                    "</tr>",
                    "{{fieldContents}}",
                    "</table>"
                ].join("");
                var content = [
                    "<tr>",
                    "<td>{{fieldName}}</td>",
                    '<td style="text-align: right;"><b>{{viewCount}}</b></td>',
                    "</tr>"
                ].join("");
                var fieldContents = "";
                $.each(
                    impactData.demographics.SpecialtyDemographics.OtherDetails,
                    function (index, value) {
                        fieldContents += content
                            .replace("{{fieldName}}", value.XValue)
                            .replace("{{viewCount}}", value.YValue);
                    }
                );
                tableTemplate = tableTemplate
                    .replace(
                        "{{otherName}}",
                        impactData.demographics.SpecialtyDemographics.Other.XValue
                    )
                    .replace(
                        "{{otherCount}}",
                        impactData.demographics.SpecialtyDemographics.Other.YValue
                    );
                tableTemplate = tableTemplate.replace(
                    "{{fieldContents}}",
                    fieldContents
                );
            }
            var specialtyData = [];
            $.each(
                impactData.demographics.SpecialtyDemographics.DemographicsDetails,
                function (index, value) {
                    specialtyData.push({
                        name: value.XValue,
                        y: value.YValue,
                        color:
                            impactData.demographics.SpecialtyDemographics.ColorCodes[index]
                    });
                }
            );
            $("#demographics-specialty").highcharts({
                credits: {
                    enabled: false
                },
                chart: {
                    type: "pie",
                    width: 250,
                    height: 310,
                    style: {
                        fontFamily: '"Open Sans", "Helvetica Neue", Helvetica, Arial',
                        fontSize: 14
                    }
                },
                title: {
                    text: null
                },
                legend: {
                    layout: "vertical",
                    itemMarginTop: 2,
                    itemMarginBottom: 2,
                    useHTML: true,
                    labelFormatter: function () {
                        return (
                            '<span style="font-weight: 600;" title="' +
                            this.name +
                            '">' +
                            trimLegendName(this.name) +
                            "</span>" +
                            " " +
                            '<b style="font-weight: 800; font-size: 14;">' +
                            this.y +
                            "</b>"
                        );
                    }
                },
                tooltip: {
                    useHTML: true,
                    borderWidth: 0,
                    shadow: false,
                    backgroundColor: "transparent",
                    formatter: function () {
                        if (
                            this.point.name == "Other" &&
                            impactData.demographics.SpecialtyDemographics.IsOtherVisible
                        ) {
                            return (
                                '<div class="t-container" style="border: 1px solid' +
                                this.point.color +
                                ';position:absolute;">' +
                                tableTemplate +
                                "</div>"
                            );
                        } else {
                            return (
                                '<div class="t-container" style="border: 1px solid' +
                                this.point.color +
                                '"><div class="t-simple">' +
                                this.point.name +
                                "<strong> " +
                                this.point.y +
                                "</strong></div></div>"
                            );
                        }
                    },
                    style: {
                        zIndex: 1000
                    }
                },
                plotOptions: {
                    pie: {
                        center: [96, 60],
                        size: 160,
                        innerSize: 102,
                        point: {
                            events: {
                                legendItemClick: function () {
                                    this.mouseOver();
                                    chart.tooltip.refresh(this);
                                    return false; // <== returning false will cancel the default action
                                }
                            }
                        },
                        allowPointSelect: true,
                        cursor: "pointer",
                        dataLabels: {
                            enabled: false
                        },
                        showInLegend: true
                    }
                },
                series: [
                    {
                        data: specialtyData
                    }
                ]
            });
        } else {
            var emptyMessage = "<p class='empty-message'>No records found</p>";
            $("#demographics-specialty").html(emptyMessage);
        }
    }

    function demographicsTopSites() {
        if (
            impactData.demographics.TopReferringSites != null &&
            impactData.demographics.TopReferringSites.IsVisible
        ) {
            var xAxisData = [];
            var yAxisData = [];
            $.each(
                impactData.demographics.TopReferringSites.DemographicsDetails,
                function (index, value) {
                    xAxisData.push(value.XValue);
                    yAxisData.push({
                        y: value.YValue
                    });
                }
            );
            $("#demographics-top-sites").highcharts({
                chart: {
                    type: "bar",
                    // width: 370, this property must be removed in order to make responsive the chart
                    height: 300,
                    marginLeft: 0,
                    style: {
                        fontFamily: '"Open Sans", "Helvetica Neue", Helvetica, Arial',
                        fontSize: 14
                    }
                },
                title: {
                    text: null
                },
                xAxis: {
                    categories: xAxisData,
                    tickWidth: 0,
                    title: {
                        text: null
                    },
                    labels: {
                        align: "left",
                        x: 0,
                        y: -18,
                        style: {
                            whiteSpace: "nowrap",
                            color: "black"
                        }
                    }
                },
                yAxis: {
                    min: 0,
                    title: {
                        enabled: false
                    },
                    labels: {
                        overflow: "justify"
                    },
                    gridLineColor: "#e0e0e0"
                },
                tooltip: {},
                plotOptions: {
                    bar: {
                        dataLabels: {
                            enabled: true,
                            style: {
                                color: "#000000",
                                fontWeight: "700",
                                fontSize: "16px",
                                lineHeight: "30px"
                            },
                            y: 1
                        },
                        pointWidth: 25
                    }
                },
                legend: {
                    enabled: false
                },
                credits: {
                    enabled: false
                },
                series: [
                    {
                        name: "Views",
                        color: "#f29400",
                        data: yAxisData
                    }
                ]
            });
        } else {
            var emptyMessage = "<p class='empty-message'>No records found</p>";
            $("#demographics-top-sites").html(emptyMessage);
        }
    }

    function demographicsIndustry() {
        if (
            impactData.demographics.IndustryDemographics != null &&
            impactData.demographics.IndustryDemographics.IsVisible
        ) {
            var otherTableData = "";
            if (impactData.demographics.IndustryDemographics.IsOtherVisible) {
                var tableTemplate = [
                    "<table>",
                    "<tr>",
                    '<th style="padding-bottom: 5px;">{{otherName}}</th>',
                    '<th style="text-align: right; padding-bottom: 10px;"><b>{{otherCount}}</b></th>',
                    "</tr>",
                    "{{fieldContents}}",
                    "</table>"
                ].join("");
                var content = [
                    "<tr>",
                    "<td>{{fieldName}}</td>",
                    '<td style="text-align: right;"><b>{{viewCount}}</b></td>',
                    "</tr>"
                ].join("");
                var fieldContents = "";
                $.each(
                    impactData.demographics.IndustryDemographics.OtherDetails,
                    function (index, value) {
                        fieldContents += content
                            .replace("{{fieldName}}", value.XValue)
                            .replace("{{viewCount}}", value.YValue);
                    }
                );
                tableTemplate = tableTemplate
                    .replace(
                        "{{otherName}}",
                        impactData.demographics.IndustryDemographics.Other.XValue
                    )
                    .replace(
                        "{{otherCount}}",
                        impactData.demographics.IndustryDemographics.Other.YValue
                    );
                otherTableData = tableTemplate.replace(
                    "{{fieldContents}}",
                    fieldContents
                );
            }
            var industryData = [];
            $.each(
                impactData.demographics.IndustryDemographics.DemographicsDetails,
                function (index, value) {
                    industryData.push({
                        name: value.XValue,
                        y: value.YValue,
                        color:
                            impactData.demographics.IndustryDemographics.ColorCodes[index]
                    });
                }
            );
            $("#demographics-industry").highcharts({
                credits: {
                    enabled: false
                },
                chart: {
                    type: "pie",
                    width: 250,
                    height: 308,
                    style: {
                        fontFamily: '"Open Sans", "Helvetica Neue", Helvetica, Arial',
                        fontSize: 14
                    }
                },
                title: {
                    text: null
                },
                legend: {
                    layout: "vertical",
                    itemMarginTop: 1,
                    itemMarginBottom: 1,
                    useHTML: true,
                    labelFormatter: function () {
                        return (
                            '<span style="font-weight: 600;" title="' +
                            this.name +
                            '">' +
                            trimLegendName(this.name) +
                            "</span>" +
                            " " +
                            '<b style="font-weight: 800; font-size: 14;">' +
                            this.y +
                            "</b>"
                        );
                    }
                },
                tooltip: {
                    useHTML: true,
                    borderWidth: 0,
                    shadow: false,
                    backgroundColor: "transparent",
                    formatter: function () {
                        if (
                            this.point.name == "Other" &&
                            impactData.demographics.IndustryDemographics.IsOtherVisible
                        ) {
                            return (
                                '<div class="t-container" style="border: 1px solid' +
                                this.point.color +
                                ';position:absolute;">' +
                                otherTableData +
                                "</div>"
                            );
                        } else {
                            return (
                                '<div class="t-container" style="border: 1px solid' +
                                this.point.color +
                                '"><div class="t-simple">' +
                                this.point.name +
                                "<strong> " +
                                this.point.y +
                                "</strong></div></div>"
                            );
                        }
                    },
                    style: {
                        zIndex: 1000
                    }
                },
                plotOptions: {
                    pie: {
                        center: [96, 60],
                        size: 160,
                        innerSize: 102,
                        point: {
                            events: {
                                legendItemClick: function () {
                                    this.mouseOver();
                                    chart.tooltip.refresh(this);
                                    return false;
                                }
                            }
                        },
                        allowPointSelect: true,
                        cursor: "pointer",
                        dataLabels: {
                            enabled: false
                        },
                        showInLegend: true
                    }
                },
                series: [
                    {
                        data: industryData
                    }
                ]
            });
        } else {
            var emptyMessage = "<p class='empty-message'>No records found</p>";
            $("#demographics-industry").html(emptyMessage);
        }
    }

    function demographicsEducation() {
        if (
            impactData.demographics.EducationDemographics != null &&
            impactData.demographics.EducationDemographics.IsVisible
        ) {
            var otherTableData = "";
            if (impactData.demographics.EducationDemographics.IsOtherVisible) {
                var tableTemplate = [
                    "<table>",
                    "<tr>",
                    '<th style="padding-bottom: 5px;">{{otherName}}</th>',
                    '<th style="text-align: right; padding-bottom: 10px;"><b>{{otherCount}}</b></th>',
                    "</tr>",
                    "{{fieldContents}}",
                    "</table>"
                ].join("");
                var content = [
                    "<tr>",
                    "<td>{{fieldName}}</td>",
                    '<td style="text-align: right;"><b>{{viewCount}}</b></td>',
                    "</tr>"
                ].join("");
                var fieldContents = "";
                $.each(
                    impactData.demographics.EducationDemographics.OtherDetails,
                    function (index, value) {
                        fieldContents += content
                            .replace("{{fieldName}}", value.XValue)
                            .replace("{{viewCount}}", value.YValue);
                    }
                );
                tableTemplate = tableTemplate
                    .replace(
                        "{{otherName}}",
                        impactData.demographics.EducationDemographics.Other.XValue
                    )
                    .replace(
                        "{{otherCount}}",
                        impactData.demographics.EducationDemographics.Other.YValue
                    );
                otherTableData = tableTemplate.replace(
                    "{{fieldContents}}",
                    fieldContents
                );
            }
            var educationData = [];
            $.each(
                impactData.demographics.EducationDemographics.DemographicsDetails,
                function (index, value) {
                    educationData.push({
                        name: value.XValue,
                        y: value.YValue,
                        color:
                            impactData.demographics.EducationDemographics.ColorCodes[index]
                    });
                }
            );
            $("#demographics-education").highcharts({
                credits: {
                    enabled: false
                },
                chart: {
                    type: "pie",
                    width: 250,
                    height: 308,
                    style: {
                        fontFamily: '"Open Sans", "Helvetica Neue", Helvetica, Arial',
                        fontSize: 14
                    }
                },
                title: {
                    text: null
                },
                legend: {
                    layout: "vertical",
                    itemMarginTop: 1,
                    itemMarginBottom: 1,
                    useHTML: true,
                    labelFormatter: function () {
                        return (
                            '<span style="font-weight: 600;" title="' +
                            this.name +
                            '">' +
                            trimLegendName(this.name) +
                            "</span>" +
                            " " +
                            '<b style="font-weight: 800; font-size: 14;">' +
                            this.y +
                            "</b>"
                        );
                    }
                },
                tooltip: {
                    useHTML: true,
                    borderWidth: 0,
                    shadow: false,
                    backgroundColor: "transparent",
                    formatter: function () {
                        if (
                            this.point.name == "Other" &&
                            impactData.demographics.EducationDemographics.IsOtherVisible
                        ) {
                            return (
                                '<div class="t-container" style="border: 1px solid' +
                                this.point.color +
                                ';position:absolute;">' +
                                otherTableData +
                                "</div>"
                            );
                        } else {
                            return (
                                '<div class="t-container" style="border: 1px solid' +
                                this.point.color +
                                '"><div class="t-simple">' +
                                this.point.name +
                                "<strong> " +
                                this.point.y +
                                "</strong></div></div>"
                            );
                        }
                    },
                    style: {
                        zIndex: 1000
                    }
                },
                plotOptions: {
                    pie: {
                        center: [96, 60],
                        size: 160,
                        innerSize: 102,
                        point: {
                            events: {
                                legendItemClick: function () {
                                    this.mouseOver();
                                    chart.tooltip.refresh(this);
                                    return false;
                                }
                            }
                        },
                        allowPointSelect: true,
                        cursor: "pointer",
                        dataLabels: {
                            enabled: false
                        },
                        showInLegend: true
                    }
                },
                series: [
                    {
                        data: educationData
                    }
                ]
            });
        } else {
            var emptyMessage = "<p class='empty-message'>No records found</p>";
            $("#demographics-education").html(emptyMessage);
        }
    }

    function demographicsPosition() {
        if (
            impactData.demographics.PositionDemographics != null &&
            impactData.demographics.PositionDemographics.IsVisible
        ) {
            var otherTableData = "";
            if (impactData.demographics.PositionDemographics.IsOtherVisible) {
                var tableTemplate = [
                    "<table>",
                    "<tr>",
                    '<th style="padding-bottom: 5px;">{{otherName}}</th>',
                    '<th style="text-align: right; padding-bottom: 10px;"><b>{{otherCount}}</b></th>',
                    "</tr>",
                    "{{fieldContents}}",
                    "</table>"
                ].join("");
                var content = [
                    "<tr>",
                    "<td>{{fieldName}}</td>",
                    '<td style="text-align: right;"><b>{{viewCount}}</b></td>',
                    "</tr>"
                ].join("");
                var fieldContents = "";
                $.each(
                    impactData.demographics.PositionDemographics.OtherDetails,
                    function (index, value) {
                        fieldContents += content
                            .replace("{{fieldName}}", value.XValue)
                            .replace("{{viewCount}}", value.YValue);
                    }
                );
                tableTemplate = tableTemplate
                    .replace(
                        "{{otherName}}",
                        impactData.demographics.PositionDemographics.Other.XValue
                    )
                    .replace(
                        "{{otherCount}}",
                        impactData.demographics.PositionDemographics.Other.YValue
                    );
                otherTableData = tableTemplate.replace(
                    "{{fieldContents}}",
                    fieldContents
                );
            }
            var positionData = [];
            $.each(
                impactData.demographics.PositionDemographics.DemographicsDetails,
                function (index, value) {
                    positionData.push({
                        name: value.XValue,
                        y: value.YValue,
                        color:
                            impactData.demographics.PositionDemographics.ColorCodes[index]
                    });
                }
            );
            $("#demographics-position").highcharts({
                credits: {
                    enabled: false
                },
                chart: {
                    type: "pie",
                    width: 250,
                    height: 308,
                    style: {
                        fontFamily: '"Open Sans", "Helvetica Neue", Helvetica, Arial',
                        fontSize: 14
                    }
                },
                title: {
                    text: null
                },
                legend: {
                    layout: "vertical",
                    itemMarginTop: 1,
                    itemMarginBottom: 1,
                    useHTML: true,
                    labelFormatter: function () {
                        return (
                            '<span style="font-weight: 600;" title="' +
                            this.name +
                            '">' +
                            trimLegendName(this.name) +
                            "</span>" +
                            " " +
                            '<b style="font-weight: 800; font-size: 14;">' +
                            this.y +
                            "</b>"
                        );
                    }
                },
                tooltip: {
                    useHTML: true,
                    borderWidth: 0,
                    shadow: false,
                    backgroundColor: "transparent",
                    formatter: function () {
                        if (
                            this.point.name == "Other" &&
                            impactData.demographics.PositionDemographics.IsOtherVisible
                        ) {
                            return (
                                '<div class="t-container" style="border: 1px solid' +
                                this.point.color +
                                ';position:absolute;">' +
                                otherTableData +
                                "</div>"
                            );
                        } else {
                            return (
                                '<div class="t-container" style="border: 1px solid' +
                                this.point.color +
                                '"><div class="t-simple">' +
                                this.point.name +
                                "<strong> " +
                                this.point.y +
                                "</strong></div></div>"
                            );
                        }
                    },
                    style: {
                        zIndex: 1000
                    }
                },
                plotOptions: {
                    pie: {
                        center: [96, 60],
                        size: 160,
                        innerSize: 102,
                        point: {
                            events: {
                                legendItemClick: function () {
                                    this.mouseOver();
                                    chart.tooltip.refresh(this);
                                    return false;
                                }
                            }
                        },
                        allowPointSelect: true,
                        cursor: "pointer",
                        dataLabels: {
                            enabled: false
                        },
                        showInLegend: true
                    }
                },
                series: [
                    {
                        data: positionData
                    }
                ]
            });
        } else {
            var emptyMessage = "<p class='empty-message'>No records found</p>";
            $("#demographics-position").html(emptyMessage);
        }
    }

    function demographicsGender() {
        if (
            impactData.demographics.GenderDemographics != null &&
            impactData.demographics.GenderDemographics.IsVisible
        ) {
            var ageRangeCatagories = [];
            var femaleData = [];
            var maleData = [];
            $.each(
                impactData.demographics.GenderDemographics.DemographicsDetails,
                function (index, value) {
                    ageRangeCatagories.push(value.AgeRange);
                    maleData.push(0 - value.MValue);
                    femaleData.push(value.FValue);
                }
            );
            var maxYaxisRange = impactData.demographics.GenderDemographics.MaxRange;
            var minYaxisRange = 0 - maxYaxisRange;
            $(document).ready(function () {
                $("#demographics-age").highcharts({
                    chart: {
                        type: "bar",
                        style: {
                            fontFamily: '"Open Sans", "Helvetica Neue", Helvetica, Arial',
                            fontSize: 14
                        }
                    },
                    title: {
                        text: null
                    },
                    xAxis: [
                        {
                            categories: ageRangeCatagories,
                            reversed: false,
                            labels: {
                                step: 1
                            },
                            lineColor: "#e0e0e0",
                            tickColor: "#e0e0e0"
                        },
                        {
                            opposite: true,
                            reversed: false,
                            categories: ageRangeCatagories,
                            linkedTo: 0,
                            labels: {
                                step: 1
                            },
                            lineColor: "#e0e0e0",
                            tickColor: "#e0e0e0"
                        }
                    ],
                    yAxis: {
                        title: {
                            text: null
                        },
                        gridLineColor: "#e0e0e0",
                        labels: {
                            formatter: function () {
                                return Math.abs(this.value);
                            }
                        },
                        min: minYaxisRange,
                        max: maxYaxisRange
                    },
                    plotOptions: {
                        series: {
                            stacking: "normal"
                        }
                    },
                    tooltip: {
                        formatter: function () {
                            return (
                                '<b style="font-weight: 600; color:' +
                                this.series.color +
                                '">' +
                                this.series.name +
                                ", age " +
                                this.point.category +
                                "</b><br/>" +
                                "Views: <b>" +
                                Highcharts.numberFormat(Math.abs(this.point.y), 0) +
                                "</b>"
                            );
                        }
                    },
                    series: [
                        {
                            name: "Male",
                            data: maleData,
                            color: "#7d7900",
                            dataLabels: {
                                enabled: true,
                                style: {
                                    color: "#7d7900",
                                    fontWeight: "700",
                                    fontSize: 16
                                },
                                inside: false,
                                x: -2,
                                formatter: function () {
                                    if (this.point.y == 0) {
                                        return;
                                    } else {
                                        return Highcharts.numberFormat(Math.abs(this.point.y), 0);
                                    }
                                }
                            }
                        },
                        {
                            name: "Female",
                            data: femaleData,
                            color: "#f29400",
                            dataLabels: {
                                enabled: true,
                                style: {
                                    color: "#f29400",
                                    fontWeight: "700",
                                    fontSize: 16
                                },
                                inside: false,
                                x: 2,
                                formatter: function () {
                                    if (this.point.y == 0) {
                                        return;
                                    } else {
                                        return Highcharts.numberFormat(Math.abs(this.point.y), 0);
                                    }
                                }
                            }
                        }
                    ]
                });
            });
        } else {
            var emptyMessage = "<p class='empty-message'>No records found</p>";
            $("#demographics-age").html(emptyMessage);
        }
    }

    function renderToolTip() {
        //tooltip on views-chart toggler
        $("#views-chart-controls > div.btn-group.pull-left").tooltip();
        $("li.pull-right.disable").tooltip();
    }

    function trimLegendName(legendName) {
        if (legendName.length > 30) {
            return jQuery.trim(legendName).substring(0, 27) + "...";
        }
        return legendName;
    }

    async function manageImpactTabNavigation() {
        if (isImpactVisited || FRConfiguration.hideImpactTab === "True") {
            return;
        }
        var urlssplits = window.location.href.split('/');
        var hashValue = urlssplits[urlssplits.length - 1];
        if (hashValue.length && hashValue.toLowerCase() == "impact") {
            loadGoogleMapsApi();

            let views = populateImpactViews();
            let demographicCheck = await populateDemographics();
            let viewsCheck = await views;
            if (viewsCheck && demographicCheck) {
                renderViewsTab();
                $tabImpact.find(".impact-topic-tabs").show();
                $tabImpact.find(".loading-wrapper").hide();
            }
            isImpactVisited = true;
        }
    }

    function bindGoogleAnalyticsTracking() {
        $("#research-topic-nav").on(
            "click",
            ".primary-tabs .impact",
            function () { }
        );
        $tabImpact.on(
            "click",
            '.topic-impact-tabs a[data-tab-type="views"]',
            function () { }
        );
        $tabImpact.on(
            "click",
            '.topic-impact-tabs a[data-tab-type="demographics"]',
            function () { }
        );
        $tabImpact.on(
            "click",
            "#views-chart-controls #views-timeline-button",
            function () { }
        );
        $tabImpact.on(
            "click",
            "#views-chart-controls #views-bar-button",
            function () { }
        );
        $tabImpact.on(
            "click",
            "#views-chart-controls #PeriodDrop li.beginning",
            function () { }
        );
        $tabImpact.on(
            "click",
            "#views-chart-controls #PeriodDrop li.year",
            function () { }
        );
        $tabImpact.on(
            "click",
            "#views-chart-controls #PeriodDrop li.month",
            function () { }
        );
    }

    const loadGoogleMapsApi = () => {
        if (typeof FRConfiguration !== 'undefined' && FRConfiguration.MapApikey) {
            const script = document.createElement("script");

            script.src = `https://maps.googleapis.com/maps/api/js?key=${FRConfiguration.MapApikey}`;
            script.async = true;
            document.head.appendChild(script);
            
            script.onload = () => {
                const mapscript = document.createElement("script");
                mapscript.src = FRConfiguration.MapJsFileurl;
                document.body.appendChild(mapscript);
            };
            
        } else {
            console.error("API key is not defined.");
        }
    };
})();
;
