var CPSU;

$(document).ready(function () {

    "use strict";

    CPSU = {

        CONSTANTS: {

            TESTING: false
        },

        VARS: {
            validNavigation: true
        },

        /*
         *   init
         *   ---------------------------------------------
         *   Starts the script
         *   ---------------------------------------------
         *   @param n/a
         *   @return Void
         */
        init: function initFn() {

            this.log('Initialising CPSU script');

            this.groundWork();
            this.bindAccordion();
            this.buildTabs();
            this.loadMenuToggle();
            this.loadFilterToggle();
            this.bindFilterSubmit();
            this.loadSelectBoxes();
            this.bindDefaultText();
            this.setUpAnalytics();
            this.bindNewsletterSignup();
            this.bindMasonry();
            this.bindTooltips();
            this.parseDynamicTool();
            this.promptBeforeClosing();
            this.bindFaqs();
            this.tableScroll();
        },

        /*
         *   log
         *   ---------------------------------------------
         *   Simple log function to keep script clean
         *   ---------------------------------------------
         *   @param String: message - Message to be logged
         *   @return Void
         */
        log: function logFn() {

            if (window.console !== undefined && this.CONSTANTS.TESTING) {

                window.console.log(arguments);
            }
        },

        tableScroll: function tableScrollFn() {
            $('tbody').on('scroll', function () {
                var cur = $(this).scrollLeft();
                var $table = $(this).parent();
                if (cur == 0) {
                    $table.addClass('arrow-right').removeClass('arrow-left');
                } else {
                    var max = $(this)[0].scrollWidth - $(this).parent().width();
                    if (cur == max) {
                        $table.addClass('arrow-left').removeClass('arrow-right');
                    } else {
                        $table.addClass('arrow-right arrow-left');
                    }
                }
            });
            $('tbody').trigger('scroll');
        },

        /*
         *   groundWork
         *   ---------------------------------------------
         *   Set Markup elements and perform ground-work
         *   ---------------------------------------------
         *   @param n/a
         *   @return Void
         */
        groundWork: function groundWorkFn() {

            $('.js-hidden').css('display', 'none');
        },

        loadSelectBoxes: function loadSelectBoxesFn() {

            var $menus = $('select'),
                max_menus = $menus.length,
                i = 0;

            //for (i; i < max_menus; i += 1) {

            //    var $menu = $($menus[i]),
            //        opt1 = $menu.find('option').get(0);

            //    $(opt1).html('Please select').attr('disabled', 'disabled');
            //}

            if ($('.select-replace').length > 0) {

                $('.select-replace').selectmenu();

                $('.select-replace').on('change', function () {

                    $(this).closest('form').submit();
                });

                // Hide submit buttons
                $('.select-replace-submit').css('display', 'none');
            }

            if (!$('html').hasClass('lt-ie9')) {

                this.log('Higer than IE8');
                $('#contact-us select').selectmenu();

            } else {

                this.log('Lower than IE9');
            }
        },

        bindAccordion: function bindAccordionFn() {
            var $article_wrap = $('.article-wrap'),
                $articles = $article_wrap.find('.article'),
                max_articles = $articles.length,
                i = 0;

            if (max_articles <= 0) return;

            this.log('Article page');

            $('.article-wrap').on('click', '.accordion-toggle-link', function (e) {

                e.preventDefault();

                var $this = $(this);

                if ($this.parent().hasClass('accordion-active')) {

                    $this.parent().removeClass('accordion-active');
                } else {

                    $this.parent().addClass('accordion-active');
                    

                    if (window.location.href.indexOf("/training/") > -1) {
                        var accordionOffset = 230;
                        $this.parent().parent().siblings().children().removeClass('accordion-active');
                    } else {
                        var accordionOffset = 110;
                        $this.parent().siblings().removeClass('accordion-active');
                    }

                    $([document.documentElement, document.body]).animate({                        
                        scrollTop: $(".accordion-active").offset().top - accordionOffset
                    }, 200);

                    //document.querySelector('.accordion-active').scrollIntoView({behavior: "smooth", block: 'start', inline: "nearest"});
                }
            });
        },

        /*
         *   buildTabs
         *   ---------------------------------------------
         *   Builds the tab systems for articles
         *   ---------------------------------------------
         *   @param TODO
         *   @return TODO
         */
        buildTabs: function buildTabsFn() {

            var that = this,
                $tab_list = $('.tabs-list'),
                $article_wrap = $('.article-wrap'),
                $articles = $article_wrap.find('.article'),
                max_articles = $articles.length,
                i = 0;

            this.log(max_articles);

            // Check page requires tabs (More than 1 article in the wrapper)
            if (max_articles <= 1) {

                return false;
            }

            // Enable the style
            $(document.body).addClass('tabs-enabled');

            // Build the tabs
            for (i; i < max_articles; i += 1) {

                var $article = $($articles[i]),
                    label = $article.find('.tab-name').text();

                $tab_list.append('<li class="tab-item" ><a role="menuitem" tabindex="0"  class="tab-link" href="#' + $article.attr('id') + '"><span class="text">' + label + '</span></a></li>');
            }

            var $tab_items = $tab_list.find('.tab-item');

            if (!$(document.body).hasClass('no-tab-pagination')) {

                var bindPagination = function (index) {

                    var $tab = $($tab_items[index]),
                        $tab_link = $tab.find('a'),

                        // Add & bind pagination
                        $pagination_wrap = $('<nav>', {
                            'class': 'tab-pagination-wrap'
                        });

                    if ($tab_items[index - 1] !== undefined) {

                        var $prev_link = $('<a>', {
                            'tabindex':'0',
                            'class': 'tab-pagination-link tab-pagination-prev',
                            'html': '<span class="chevron">&lt;&nbsp;</span><span class="direction">&nbsp;Previous:&nbsp;</span><span class="pag-name">' + $($tab_items[index - 1]).find('.text').html() + '</span>',
                            click: function () {

                                window.location.href = '#skip-to-content';
                                that.loadTab($articles, $($tab_items[index - 1]), true);
                            },
                            keypress: function () {

                                window.location.href = '#skip-to-content';
                                that.loadTab($articles, $($tab_items[index - 1]), true);
                            }
                        });
                        $pagination_wrap.append($prev_link);
                    }

                    if ($tab_items[index + 1] !== undefined) {

                        var $next_link = $('<a>', {
                            'tabindex': '0',
                            'class': 'tab-pagination-link tab-pagination-next',
                            'html': '<span class="pag-name"><label class="direction">Next:&nbsp;</label>&nbsp;' + $($tab_items[index + 1]).find('.text').html() + ' </span><span class="chevron">&nbsp;&nbsp;&gt;</span>',
                            click: function () {

                                window.location.href = '#skip-to-content';
                                that.loadTab($articles, $($tab_items[index + 1]), true);

                            },
                            keypress: function () {

                                window.location.href = '#skip-to-content';
                                that.loadTab($articles, $($tab_items[index + 1]), true);

                            }
                        });

                        $pagination_wrap.append($next_link);
                    }
                    $($articles[index]).append($pagination_wrap);
                };

                for (var count = 0; count < $tab_items.length; count += 1) {

                    bindPagination(count);
                }
            }



            $('.tab-link').on('click', function (e) {

                e.preventDefault();

                var $this = $(this),
                    location = $this.attr('href');

                that.loadTab($articles, $this.parent('li'), {
                    'animate': false
                });
            });

            // Load first element, else the hash tag from page load
            if (window.location.hash) {

                for (var j = 0; j < $tab_items.length; j += 1) {

                    var $tab_item = $($tab_items[j]),
                        potential_tab = $tab_item.find('a').attr('href');

                    if (potential_tab === window.location.hash) {

                        this.loadTab($articles, $tab_item, {
                            'animate': 'false'
                        });
                    }
                }

            } else {

                // Select first tab element
                this.loadTab($articles, $('.tab-item').first(), {
                    'animate': 'false',
                    'first': true
                });
            }
        },

        loadTab: function loadTabFn($articles, $tab, options) {

            // Find if an article matches the clicked tab
            var $link = $tab.find('a');

            for (var i = 0; i < $articles.length; i += 1) {

                var $article = $($articles[i]);

                if ("#" + $article.attr('id') === $link.attr('href')) {

                    $tab.addClass('active').siblings().removeClass('active');

                    $article.addClass('active').siblings().removeClass('active');

                    if (options !== undefined && options.first === true) {

                        this.log('Do not animate');

                    } else {

                        $(window).scrollTo('#article-top', 350);
                    }
                }
            }
        },

        loadMenuToggle: function loadMenuToggleFn() {

            var that = this,
                $toggleLink = $('.toggle-link, .nav__toggle');

            if ($toggleLink.length > 0) {

                $('html').on('click', function () {

                    if ($toggleLink.parent('.nav').hasClass('active')) {

                        that.log('Hiding nav');
                        $toggleLink.parent('.nav').removeClass('active');
                    }
                });

                $('.inner-nav, .inner').on('click', function (e) {

                    e.stopPropagation();
                });

                $toggleLink.on('click', function (e) {

                    e.preventDefault();
                    e.stopPropagation();

                    $(this).parent('.nav').toggleClass('active');

                    that.log('Toggling nav');
                });
            }
        },

        loadFilterToggle: function loadFilterToggleFn() {

            var that = this;
            if (!$('.filter').length) return;


            this.log('Filter on this page');

            if ($('.filter').closest('form').hasClass('filtered')) {
                $('.filter-wrap').get(0).scrollIntoView();
            }

            $('.filter-nav').on('click', '.nav-item', function (e) {

                that.log('Clicked filter toggle');

                e.preventDefault();

                var $this = $(this),
                    filter = $this.attr('rel');

                if ($this.hasClass('active')) {

                    $this.removeClass('active');
                    $(filter).removeClass('active');
                    $('.filter-wrap').removeClass('active-filter');                    

                } else {

                    $this.addClass('active').siblings().removeClass('active');
                    $(filter).addClass('active').siblings().removeClass('active');
                    $('.filter-wrap').addClass('active-filter');
                }
            });
        },

        bindFilterSubmit: function bindFilterSubmitFn() {

            var $form = $('.filter-form');

            if (!$form.length) return;

            $form.find('.filter-item').on('click', '.radio', function (e) {

                $form.submit();
            });
        },

        bindDefaultText: function bindDefaultTextFn() {

            var $input = $('.default-text'),
                that = this;

            if (!$input.length) return;

            var placeholderAttr = $input.attr('placeholder');

            that.log('Default text on this page');

            if ($input.val() === "") $input.val(placeholderAttr);

            $input.on('blur', function () {

                if ($(this).val() === "") $(this).val(placeholderAttr);
            });

            $input.on('focus', function () {

                if ($(this).val() === placeholderAttr) $(this).val("");
            });

            $('.nav-search').on('submit', '.nav-search-form', function (e) {

                var $search = $(this).find('.search-input');

                if ($search.val() === $search.attr('placeholder')) {

                    that.log('Do not submit form');
                    e.preventDefault();
                }

            });
        },

        getTransitionEndEvent: function getTransitionEndEventFn() {
            var t,
                el = document.createElement('fakeelement'),
                transitions = {
                    'transition': 'transitionend',
                    'OTransition': 'oTransitionEnd',
                    'MozTransition': 'transitionend',
                    'WebkitTransition': 'webkitTransitionEnd'
                };

            for (t in transitions) {
                if (el.style[t] !== undefined) {
                    return transitions[t];
                }
            }
        },

        /*
         *   @title bindNewsletterSignup
         *   ---------------------------------------------------
         *   Replaces default form behavior with AJAX submission
         *   Ensures form is valid and submits
         *   ---------------------------------------------------
         *   @author Alex Coady <acoady@thisiszone.com>
         *   @date 30/07/2013
         *   @param n/a
         *   @return (Void) Binds form action
         */
        bindNewsletterSignup: function bindNewsletterSignupFn() {

            var that = this,
                $widget = $('.widget--newsletter');

            if (!$widget.length) return;

            this.log("Newletter signup forn on page");

            var $form = $widget.find('form');

            $form.on('submit', function (e) {

                e.preventDefault();
                $form.validate();

                if ($form.valid()) {

                    $.ajax({
                        "type": "POST",
                        "url": $form.attr("action"),
                        "data": $form.serialize(),
                        success: function (response, statusText, xhr) {

                            $widget.html(response);
                        },
                        error: function (xhr, statusText, exceptiontext) {
                            that.log(xhr, statusText, exceptiontext);
                        }
                    });
                }
            });
        },

        /*
         *   Function bindTooltips
         *   ---------------------------------------------------
         *   Finds tooltip triggers and binds their clicking to
         *   open a corresponding tooltip. The HREF element of
         *   the trigger link must be the ID of the tooltip.
         *   ---------------------------------------------------
         *   @param n/a
         *   @return
         */
        bindTooltips: function bindTooltipsFn() {

            /* ----- Kick back -------------------------------------------- */
            if (!$('.tooltip').length || !$('.tooltip-link').length) return;
            /* ----- Kick back -------------------------------------------- */

            this.log("Tooltip(s) on page");
            var that = this;

            $('.tooltip-link').on('click', function (ev) {

                ev.preventDefault();

                var $tooltip = $($(this).attr('href'));

                /* ----- Kick back ------- */
                if (!$tooltip.length) return;
                /* ----- Kick back ------- */

                $tooltip.addClass('active');

                // Ensure correct vertical positioning
                $tooltip.css("margin-top", function calcMarginTop() {

                    return (($tooltip.height() / 2) * -1) + "px";
                });

                $('.tooltip-overlay').addClass('active');

                $('.tooltip-overlay, .tooltip__close').one('click', function (ev) {

                    ev.preventDefault();
                    closeTooltip();
                });

                function closeTooltip() {

                    // Deactivate classes
                    $tooltip.removeClass('active');
                    $('.tooltip-overlay').removeClass('active');

                    // Remove close binding
                    $('.tooltip-overlay, .tooltip__close').off('click');
                }
            });
        },


        /*
         *   Function bindMasonry
         *   ---------------------------------------------------
         *   @param n/a
         *   @return
         */
        bindMasonry: function bindMasonryFn() {

            if (!$('.masonry').length) return;

            this.log("Masonry on page");

            setTimeout(function () {
                var container = document.querySelector('.masonry');
                var msnry = new Masonry(container);
            }, 500);



            $('.masonry').css('padding-bottom', '40px');
        },

        /*
         *   Function parseDynamicTool
         *   ----------------------------------------------------
         *   Takes the DynamicTool page and builds tool from markup
         *   ----------------------------------------------------
         *   @param n/a
         *   @return (Void) Parses tool
         */
        parseDynamicTool: function parseDynamicToolFn() {

            if (!$('#dynamic-tool').length) return;

            var that = this,
                $tool = $('#dynamic-tool'),

                $categories = $tool.find('.category'),
                category_count = $categories.length,
                category_i = 0,
                categories = [],

                $nav = $('#tool__nav'),

                CategoryPage = function ($el, index, name, url, $nav_item) {

                    this.$el = $el;
                    this.index = index;
                    this.name = name;
                    this.url = url;
                    this.$nav_item = $nav_item;
                };

            CategoryPage.prototype = {

                get: function getFn(property) {

                    return this[property];
                },

                set: function setFn(property, value) {

                    this[property] = value;
                    $(this).trigger("changed");
                    return this;
                },

                makeActive: function makeActiveFn() {

                    this.$el.addClass('active');
                    this.$el.siblings().removeClass('active');

                    this.$nav_item.addClass('active');
                    this.$nav_item.siblings().removeClass('active');
                },

                drawPagination: function drawPaginationFn() {

                    var collection = CategoryPage.collection,
                        category = this,
                        $pagination = this.$el.find('.dynamic-tool__pagination');

                    if (this.get("index") > 0) {

                        var link_title = '<span class="pag-direction">Previous</span> <span class="pag-name">' + category.get("index") + ': ' + collection[category.get("index") - 1].get("name") + '</span>',
                            $pag_prev = $('<a href="#" class="pag-item prev"><i class="icon">&lt;</i>' + link_title + '</a>')
                                .on('click', $pag_prev, function clickPrevFn(e) {

                                    e.preventDefault();
                                    document.location.hash = collection[category.get("index") - 1].get("url");
                                });

                    } else {

                        var link_title = '<span class="pag-direction">Previous</span>',
                            $pag_prev = $('<a href="#" class="pag-item disabled prev"><i class="icon">&lt;</i>' + link_title + '</a>')
                                .on('click', $pag_prev, function clickPrevFn(e) {

                                    e.preventDefault();
                                });
                    }

                    // $pagination.append($pag_prev);

                    if ((collection.length - this.get("index") - 1) > 0) {

                        var link_title = '<span class="pag-direction">Next</span> <span class="pag-name">' + (+category.get("index") + 2) + ': ' + collection[category.get("index") + 1].get("name") + '</span>',
                            $pag_next = $('<a href="#" class="pag-item next">' + link_title + '<i class="icon">&gt;</i></a>')
                                .on('click', $pag_next, function clickNextFn(e) {
                                    $(window).scrollTop(0);

                                    e.preventDefault();
                                    document.location.hash = collection[category.get("index") + 1].get("url");
                                });

                    } else {

                        var link_title = '<span class="pag-direction">Next</span><span class="pag-name">&nbsp;See your results</span>',
                            $pag_next = $('<a href="#" class="pag-item next">' + link_title + '<i class="icon">&gt;</i></a>')
                                .on('click', $pag_next, function clickNextFn(e) {

                                    $tool.find("form").submit();
                                    e.preventDefault();
                                });
                    }
                    $pagination.append($('<span class="cat-status">' + category.get('status') + '</span>'));
                    $pagination.append($pag_prev);
                    $pagination.append($pag_next);
                }
            };

            // Loop through categories and build tabs/pages
            for (category_i; category_i < category_count; category_i += 1) {

                var category = new CategoryPage();

                categories.push(this.parseDynamicToolCategory(category, $categories, category_i, $nav));
            }
            CategoryPage.collection = categories;

            // Paginaton
            if ($tool.hasClass("dynamic-tool--pagination")) {

                this.log("Dynamic tool has pagination");

                for (category_i = 0; category_i < category_count; category_i += 1) {

                    categories[category_i].drawPagination();
                }
            }


            // Bind window to watch for hashchange events
            $(window).on('hashchange', function () {

                var hash = document.location.hash.substring(1);

                $(categories).each(function (i, ctgry) {

                    if (ctgry.get("url") === hash) {

                        ctgry.makeActive();
                        // $('.utility-button--save').trigger('click');
                        return true;
                    }
                });
            });

            // Load first/selected intiial category
            if (window.location.hash !== "") {

                $(window).trigger('hashchange');
            } else {

                categories[0].makeActive();
            }

            this.bindDynamicToolSave($tool);
        },

        /*
         *   @title bindDynamicToolSave
         *   ----------------------------------------------------
         *   Asyncronously submits save form
         *   ----------------------------------------------------
         *   @author Alex Coady <acoady@thisiszone.com>
         *   @date 06/08/2013
         *   @param null
         *   @return (Void) Submits form
         */
        bindDynamicToolSave: function bindDynamicToolSaveFn($tool) {

            var that = this,
                form = $tool.find("form")[0],
                data,
                $saveEmail = $('.utility-button--save');

            $saveEmail.on('click', function (e) {

                if ($(this).hasClass('no-id')) {

                    e.preventDefault();

                    that.log("no id!");
                    saveToolProgress();
                    return false;

                } else {

                    that.log("has id");
                }

                return true;
            });

            $(form).on('change', '.check', function (ev) {

                CPSU.VARS.validNavigation = false;
                saveToolProgress();
            });

            function saveToolProgress() {

                var data = $(form).serialize();

                $.ajax({
                    "type": "POST",
                    "url": "/umbraco/Surface/OnlineAssessmentToolSurface/SaveForm",
                    "data": data,
                    success: function saveDynamicToolSuccessFn(response, status, jqXHR) {

                        if ($('.no-id').length) {

                            var href = $('.utility-button--save.no-id').attr("href");
                            href += response.assessmentId;

                            $('.no-id').attr("href", href)
                                .removeClass('no-id');

                            $saveEmail.trigger('click');

                            displaySavedToolURL(href);

                        }
                    },
                    error: function saveDynamicToolErrorFn(jqXHR, status, errorThrown) {

                        that.log(jqXHR, status, errorThrown);
                    },
                });
            };

            function displaySavedToolURL(href) {
                var toolName = $tool.data('tool-name');
                href = href.replace('mailto:?subject=My Assessment Url&body=My Online ' + toolName + ' Url is ', '');
                $('nav.dynamic-tool__options').after('<h2 class="heading heading--sub">Your ' + toolName + ' URL</h2><p class="assessmentUrl-descrtiption">Don&rsquo;t forget to make a note of your unique URL which you can use to come back to your saved overview page:</p><p id="assessmentUrl"><a href="' + href + '">' + href + '</a></p>');
            };
        },

        /*
         *   Function parseDynamicToolQuestion
         *   ----------------------------------------------------
         *   Parses a question into a JS accordion device
         *   ----------------------------------------------------
         *   @author Alex Coady <acoady@thisiszone.com>
         *   @date 01/08/2013
         *   @param n/a
         *   @return (Void) Parses question
         */
        parseDynamicToolQuestion: function parseDynamicToolQuestionFn(question, first) {

            var that = this,
                $question = $(question),
                $toggle = $question.find('.toggle-more');

            // if (first) {
            //     $question.addClass('active');
            // }

            $toggle.on('click', function (e) {

                e.preventDefault();
                that.log('Toggle question accordion');

                if (!$question.hasClass('active')) {

                    $question.addClass('active');
                    $question.siblings().removeClass('active');

                } else {

                    $question.removeClass('active');
                }
            });
        },

        /*
         *   @title promptBeforeClosing
         *   ----------------------------------------------------
         *   Prompts user to do save before closing tab or window
         *   ----------------------------------------------------
         *   @author Tim Reed <treed@thisiszone.com>
         *   @date   07/03/2014
         *   @param  (Category)  category: Empty category object
         */
        promptBeforeClosing: function promptBeforeClosingFn() {

            $("a").click(setValid);

            function setValid() {

                CPSU.VARS.validNavigation = true;
            }

            function endSession() { }

            function wireUpEvents() {
                /*
                 * For a list of events that triggers onbeforeunload on IE
                 * check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
                 */

                if ($('body').hasClass('dynamic-tool--self-assessment-tool')) {

                    window.onbeforeunload = function (e) {
                        var e = e || window.event;


                        if (CPSU.VARS.validNavigation === false) {
                            $('#assessmentUrl').addClass('attention');

                            //IE & Firefox
                            if (e) {
                                e.returnValue = "Have you made a note of your unique Self assessment URL? If you navigate away from this page you will lose this.";
                            }

                            // For Safari
                            return endSession();
                        }
                    };

                }

            }
            wireUpEvents();

        },

        /*
         *   @title parseDynamicToolCategory
         *   ----------------------------------------------------
         *   Parses an DynamicTool category into a tab/page
         *   ----------------------------------------------------
         *   @author Alex Coady <acoady@thisiszone.com>
         *   @date   01/08/2013
         *   @param  (Category)  category: Empty category object
         *   @param  ($)         $categories: Category DOM elements
         *   @param  (Int)       category_i: Category index
         *   @param  ($)         $nav: Nav DOM element
         *   @return (Category)  Complete category object
         */
        parseDynamicToolCategory: function parseDynamicToolCategoryFn(category, $categories, category_i, $nav) {

            var that = this,
                $category = $($categories[category_i]),
                category_name = $category.find('.category__heading').text(),
                category_url = $category.data('url'),

                category_count = $categories.length,

                $questions = $category.find('.question'),
                question_count = $questions.length,
                question_i = 0,

                $navItem = $('<li class="nav__item"><a class="nav__link" href="#">' + category_name + '</a></li>').on('click', function (e) {

                    e.preventDefault();
                    document.location.hash = category_url;
                });

            $nav.append($navItem);

            // Loop through questions and build accordion
            for (question_i; question_i < question_count; question_i += 1) {

                // Passes boolean as 2nd parameter based on whether this is the first question.
                this.parseDynamicToolQuestion($questions[question_i], (question_i === 0));
            }

            // Set first question to active
            //$( $questions[0] ).addClass('active');

            category.set("$el", $category);
            category.set("index", category_i);
            category.set("name", category_name);
            category.set("url", category_url);
            category.set("$nav_item", $navItem);
            category.set("status", $category.data("status"));

            return category;
        },

        setUpAnalytics: function setUpAnalyticsFn() {
            // Get all links that end in downloadable file extensions, that don't already have GA tracking code, and attach a custom Google Analytics even to the click event
            $('a').filter(function () {
                return $(this).attr('href') !== undefined &&
                    $(this).attr('href').match(/\.(pdf|PDF|doc|DOC|docx|DOCX|xls|XLS|xlsx|XLSX|zip|ZIP)/) &&
                    ($(this).attr('onclick') === undefined ||
                        $(this).attr('onclick').match(/\.(gaq)/)
                    );
            }).on("click", function () {
                var fileName = $(this).attr('href');
                var fileExtension = fileName.split('.').pop();
                _gaq.push(['_trackEvent', 'Download', fileExtension, fileName]);
            });
        },

        bindFaqs: function bindFaqs() {

            var questions = $('article.faqs').find('.question');
            for (var i = 0; i < questions.length; i++) {
                this.parseDynamicToolQuestion(questions[i]);
            }
        }
    };

    $('.featured-resource-item.module--featured-content').each(function (i) {
        if (!$(this).hasClass('three-columns')) {
            return false;
        }

        var columnChecker = (i + 1) % 3;

        if (columnChecker == 1 || i == 0) {
            $(this).addClass('first-column');
        }

        if (columnChecker == 2) {
            $(this).addClass('second-column');
        }

        if (columnChecker == 0) {
            $(this).addClass('third-column');
        }
    });

    // OneTrust cookie consent 
    $('iframe').each(function () {
        if ($(this)[0].src.includes('audioboom')) {
            $(this).after("<div class='audioboom--widget widget widget--simple-box'></div>");
            $('.audioboom--widget').load(window.location.protocol + "//"+ window.location.host +"/consentplaceholders/consent-placeholder-audioboom.html");
        } 
        else if ($(this)[0].src.includes('youtube')) {
            $(this).after("<div class='youtube--widget widget--simple-box'></div>");
            $('.youtube--widget').load(window.location.protocol + "//" + window.location.host +"/consentplaceholders/consent-placeholder-youtube.html");
        }
        else if ($(this)[0].dataset && $(this)[0].dataset.src && $(this)[0].dataset.src.includes('youtube')) {
            $(this).after("<div class='youtube--widget widget--simple-box'></div>");
            $('.youtube--widget').load(window.location.protocol + "//" + window.location.host + "/consentplaceholders/consent-placeholder-youtube.html");
        } else if ($(this)[0].id.includes('recaptcha')) {
            $(this).wrap('<script type="text/x-metomic" data-micropolicy="functional" data-placeholder="' + window.location.origin + '/consentplaceholders/consent-placeholder-recaptcha.html" crossorigin />')
        }
    });
    OptanonWrapper(); // re-fire OneTrust banner event to hide consent placeholders if cookies have been accepted
    //$('#g-recaptcha').wrap('<script type="text/x-metomic" data-micropolicy="functional" data-placeholder="' + window.location.origin + '/consentplaceholders/consent-placeholder-recaptcha.html" crossorigin />')

    CPSU.init();


  
});
function RedirectSearch(ctrlId) {
    var term = $('#' + ctrlId).val();
    if (term != '') {
        document.location.href = '/Search/?term=' + encodeURI(term);
    }
}

$(document).ready(function () {

    var $searchContainer = $('.site-row--page-navigation .grid-wrap .search-box-container');
    var $searchResultsSuggest = $('.search-results-suggest');

    $('#search-button, #search-button-mobile').on('click', function (e) {
        if ($searchContainer.is(':visible')) {
            if (window.location.pathname.split('/')[1] !== 'Search') { // only show nav search bar if not on search results page
                $searchContainer.hide();
            }
        } else {
            if (window.location.pathname.split('/')[1] !== 'Search') { // only show nav search bar if not on search results page
                $searchContainer.show();
            }
            $('.nav-search .search-input').focus(); // will focus on search listing search bar if on search results page, else focus on nav search bar
        }
        e.stopPropagation();
        
    });

    $('#searchBarAppNav, #searchBarAppListing').click(function (e) { // combined with $(window).click prevents search bar closing before button can be clicked
        e.stopPropagation();
    });    

    $(window).click(function (e) {
        if (!e.relatedTarget) {
            $searchContainer.hide();
            $searchResultsSuggest.hide();
            return;
        }

        var $target = $(e.relatedTarget);
        if (!$searchContainer.has($target)) {
            $searchContainer.hide();
            $searchResultsSuggest.hide();
            return;
        }
    });

    $('.search-input').focus(function () {
        $searchResultsSuggest.show(); // re-show suggestions container after hidden by above $(window).click
    })
});

function debounce(func, wait, immediate) {
    var timeout;

    return function () {
        var context = this, args = arguments;
        var later = function () {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
}


jQuery.fn.putCursorAtEnd = function () {

    return this.each(function () {

        // Cache references
        var $el = $(this),
            el = this;

        // Only focus if input isn't already
        if (!$el.is(":focus")) {
            $el.focus();
        }

        // If this function exists... (IE 9+)
        if (el.setSelectionRange) {

            // Double the length because Opera is inconsistent about whether a carriage return is one character or two.
            var len = $el.val().length * 2;

            // Timeout seems to be required for Blink
            setTimeout(function () {
                el.setSelectionRange(len, len);
            }, 1);

        } else {

            // As a fallback, replace the contents with itself
            // Doesn't work in Chrome, but Chrome supports setSelectionRange
            $el.val($el.val());

        }

        // Scroll to the bottom, in case we're in a tall textarea
        // (Necessary for Firefox and Chrome)
        this.scrollTop = 999999;

    });

};
function RedirectSearch(ctrlId) {
    var term = $('#' + ctrlId).val();
    if (term != '') {
        document.location.href = '/Search/?term=' + encodeURI(term);
    }
}

$(document).ready(function () {

    var $searchContainerIE = $('.search-box-container-ie');

    $('#search-button-ie').on('click', function () {
        $searchContainerIE.show();
        $('#site-search-ie').focus();
    });

    $('#site-search-ie').on('blur', function (e) {
        if (!e.relatedTarget) {
            $searchContainerIE.hide();
            return;
        }

        var $target = $(e.relatedTarget);
        if (!$searchContainerIE.has($target)) {
            $searchContainerIE.hide();
            return;
        }
    });
});

function debounce(func, wait, immediate) {
    var timeout;

    return function () {
        var context = this, args = arguments;
        var later = function () {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
}

$(document).on("click",
    "#SearchSuggestBtn",
    function (e) {
        e.preventDefault();
        var form = $(this).closest('form');
        $(form).submit();
    });

$(document).on("keyup",
    "#SearchTerm",
    debounce(function (e) {
        e.preventDefault();
        var term = $('#SearchTerm').val();
        if (!isBlank(term)) {
            $('#frmSearchMain').submit();
        }
    },
        300));

$(document).on("input",
    "#site-search-ie",
    debounce(function (e) {
        e.preventDefault();

        var term = $('#site-search-ie').val();
        if (!isBlank(term) && term.length >= 3) {
            var data = { Name: $('#site-search-ie').val() };

            $.ajax({
                type: "POST",
                url: '/umbraco/Surface/SearchSurface/SubmitSearchSuggestForm?term=' + $('#site-search-ie').val(),
                data: data,
                datatype: "html",
                success: function (data) {
                    $('#search-results-suggest').html(data);
                },
                error: function () {
                    //alert("error!");
                }
            });
        } else {
            $('#search-results-suggest').html('');
        }
    },
        300));

function isBlank(str) {
    return (!str || /^\s*$/.test(str));
}

// arrow key navigation
$('input').keydown(function () {
    console.log('Hi 1');
    //    var key = e.keyCode;
    //
    //    if (key !== 40 && key !== 38) return;
    //
    //    var $listItems = $('.searchTerm');
    //    var $selected = $listItems.filter('.selected');
});


$(document).on("keydown",
    "#site-search-ie",
    function (e) {
        var key = e.keyCode;

        if (key !== 40 && key !== 38) return;

        var $searchSuggestions = $('.searchTerm');
        var $selected = $searchSuggestions.filter('.selected');

        $searchSuggestions.removeClass('selected');

        if (key === 40) // Down key
        {
            if ($selected.parent().is(':last-child')) {
                // at bottom of the list
                $current = $selected.eq(0);
            }
            else if (!$selected.length) {
                // at top of the list
                $current = $searchSuggestions.eq(0);
                $('#userSearchTerm')[0].innerText = $('#site-search-ie').val(); // store the user's search term
            }
            else {
                $current = $selected.parent().next().children();
            }
        } else if (key == 38) // Up key
        {
            if (!$selected.length || $selected.parent().is(':first-child')) {
                // at top of the list
                $('#site-search-ie').val($('#userSearchTerm')[0].innerText); // put the user's search term back in the input
                $current = null;
            }
            else {
                $current = $selected.parent().prev().children();
            }
        }

        if ($current != null) {
            $current.addClass('selected');
            $('#site-search-ie').val($current[0].innerText);
        }

        $('#site-search-ie').putCursorAtEnd();
    });


jQuery.fn.putCursorAtEnd = function () {

    return this.each(function () {

        // Cache references
        var $el = $(this),
            el = this;

        // Only focus if input isn't already
        if (!$el.is(":focus")) {
            $el.focus();
        }

        // If this function exists... (IE 9+)
        if (el.setSelectionRange) {

            // Double the length because Opera is inconsistent about whether a carriage return is one character or two.
            var len = $el.val().length * 2;

            // Timeout seems to be required for Blink
            setTimeout(function () {
                el.setSelectionRange(len, len);
            }, 1);

        } else {

            // As a fallback, replace the contents with itself
            // Doesn't work in Chrome, but Chrome supports setSelectionRange
            $el.val($el.val());

        }

        // Scroll to the bottom, in case we're in a tall textarea
        // (Necessary for Firefox and Chrome)
        this.scrollTop = 999999;

    });

};
/*! tooltipster v4.2.6 */!function(a,b){"function"==typeof define&&define.amd?define(["jquery"],function(a){return b(a)}):"object"==typeof exports?module.exports=b(require("jquery")):b(jQuery)}(this,function(a){function b(a){this.$container,this.constraints=null,this.__$tooltip,this.__init(a)}function c(b,c){var d=!0;return a.each(b,function(a,e){return void 0===c[a]||b[a]!==c[a]?(d=!1,!1):void 0}),d}function d(b){var c=b.attr("id"),d=c?h.window.document.getElementById(c):null;return d?d===b[0]:a.contains(h.window.document.body,b[0])}function e(){if(!g)return!1;var a=g.document.body||g.document.documentElement,b=a.style,c="transition",d=["Moz","Webkit","Khtml","O","ms"];if("string"==typeof b[c])return!0;c=c.charAt(0).toUpperCase()+c.substr(1);for(var e=0;e<d.length;e++)if("string"==typeof b[d[e]+c])return!0;return!1}var f={animation:"fade",animationDuration:350,content:null,contentAsHTML:!1,contentCloning:!1,debug:!0,delay:300,delayTouch:[300,500],functionInit:null,functionBefore:null,functionReady:null,functionAfter:null,functionFormat:null,IEmin:6,interactive:!1,multiple:!1,parent:null,plugins:["sideTip"],repositionOnScroll:!1,restoration:"none",selfDestruction:!0,theme:[],timer:0,trackerInterval:500,trackOrigin:!1,trackTooltip:!1,trigger:"hover",triggerClose:{click:!1,mouseleave:!1,originClick:!1,scroll:!1,tap:!1,touchleave:!1},triggerOpen:{click:!1,mouseenter:!1,tap:!1,touchstart:!1},updateAnimation:"rotate",zIndex:9999999},g="undefined"!=typeof window?window:null,h={hasTouchCapability:!(!g||!("ontouchstart"in g||g.DocumentTouch&&g.document instanceof g.DocumentTouch||g.navigator.maxTouchPoints)),hasTransitions:e(),IE:!1,semVer:"4.2.6",window:g},i=function(){this.__$emitterPrivate=a({}),this.__$emitterPublic=a({}),this.__instancesLatestArr=[],this.__plugins={},this._env=h};i.prototype={__bridge:function(b,c,d){if(!c[d]){var e=function(){};e.prototype=b;var g=new e;g.__init&&g.__init(c),a.each(b,function(a,b){0!=a.indexOf("__")&&(c[a]?f.debug&&console.log("The "+a+" method of the "+d+" plugin conflicts with another plugin or native methods"):(c[a]=function(){return g[a].apply(g,Array.prototype.slice.apply(arguments))},c[a].bridged=g))}),c[d]=g}return this},__setWindow:function(a){return h.window=a,this},_getRuler:function(a){return new b(a)},_off:function(){return this.__$emitterPrivate.off.apply(this.__$emitterPrivate,Array.prototype.slice.apply(arguments)),this},_on:function(){return this.__$emitterPrivate.on.apply(this.__$emitterPrivate,Array.prototype.slice.apply(arguments)),this},_one:function(){return this.__$emitterPrivate.one.apply(this.__$emitterPrivate,Array.prototype.slice.apply(arguments)),this},_plugin:function(b){var c=this;if("string"==typeof b){var d=b,e=null;return d.indexOf(".")>0?e=c.__plugins[d]:a.each(c.__plugins,function(a,b){return b.name.substring(b.name.length-d.length-1)=="."+d?(e=b,!1):void 0}),e}if(b.name.indexOf(".")<0)throw new Error("Plugins must be namespaced");return c.__plugins[b.name]=b,b.core&&c.__bridge(b.core,c,b.name),this},_trigger:function(){var a=Array.prototype.slice.apply(arguments);return"string"==typeof a[0]&&(a[0]={type:a[0]}),this.__$emitterPrivate.trigger.apply(this.__$emitterPrivate,a),this.__$emitterPublic.trigger.apply(this.__$emitterPublic,a),this},instances:function(b){var c=[],d=b||".tooltipstered";return a(d).each(function(){var b=a(this),d=b.data("tooltipster-ns");d&&a.each(d,function(a,d){c.push(b.data(d))})}),c},instancesLatest:function(){return this.__instancesLatestArr},off:function(){return this.__$emitterPublic.off.apply(this.__$emitterPublic,Array.prototype.slice.apply(arguments)),this},on:function(){return this.__$emitterPublic.on.apply(this.__$emitterPublic,Array.prototype.slice.apply(arguments)),this},one:function(){return this.__$emitterPublic.one.apply(this.__$emitterPublic,Array.prototype.slice.apply(arguments)),this},origins:function(b){var c=b?b+" ":"";return a(c+".tooltipstered").toArray()},setDefaults:function(b){return a.extend(f,b),this},triggerHandler:function(){return this.__$emitterPublic.triggerHandler.apply(this.__$emitterPublic,Array.prototype.slice.apply(arguments)),this}},a.tooltipster=new i,a.Tooltipster=function(b,c){this.__callbacks={close:[],open:[]},this.__closingTime,this.__Content,this.__contentBcr,this.__destroyed=!1,this.__$emitterPrivate=a({}),this.__$emitterPublic=a({}),this.__enabled=!0,this.__garbageCollector,this.__Geometry,this.__lastPosition,this.__namespace="tooltipster-"+Math.round(1e6*Math.random()),this.__options,this.__$originParents,this.__pointerIsOverOrigin=!1,this.__previousThemes=[],this.__state="closed",this.__timeouts={close:[],open:null},this.__touchEvents=[],this.__tracker=null,this._$origin,this._$tooltip,this.__init(b,c)},a.Tooltipster.prototype={__init:function(b,c){var d=this;if(d._$origin=a(b),d.__options=a.extend(!0,{},f,c),d.__optionsFormat(),!h.IE||h.IE>=d.__options.IEmin){var e=null;if(void 0===d._$origin.data("tooltipster-initialTitle")&&(e=d._$origin.attr("title"),void 0===e&&(e=null),d._$origin.data("tooltipster-initialTitle",e)),null!==d.__options.content)d.__contentSet(d.__options.content);else{var g,i=d._$origin.attr("data-tooltip-content");i&&(g=a(i)),g&&g[0]?d.__contentSet(g.first()):d.__contentSet(e)}d._$origin.removeAttr("title").addClass("tooltipstered"),d.__prepareOrigin(),d.__prepareGC(),a.each(d.__options.plugins,function(a,b){d._plug(b)}),h.hasTouchCapability&&a(h.window.document.body).on("touchmove."+d.__namespace+"-triggerOpen",function(a){d._touchRecordEvent(a)}),d._on("created",function(){d.__prepareTooltip()})._on("repositioned",function(a){d.__lastPosition=a.position})}else d.__options.disabled=!0},__contentInsert:function(){var a=this,b=a._$tooltip.find(".tooltipster-content"),c=a.__Content,d=function(a){c=a};return a._trigger({type:"format",content:a.__Content,format:d}),a.__options.functionFormat&&(c=a.__options.functionFormat.call(a,a,{origin:a._$origin[0]},a.__Content)),"string"!=typeof c||a.__options.contentAsHTML?b.empty().append(c):b.text(c),a},__contentSet:function(b){return b instanceof a&&this.__options.contentCloning&&(b=b.clone(!0)),this.__Content=b,this._trigger({type:"updated",content:b}),this},__destroyError:function(){throw new Error("This tooltip has been destroyed and cannot execute your method call.")},__geometry:function(){var b=this,c=b._$origin,d=b._$origin.is("area");if(d){var e=b._$origin.parent().attr("name");c=a('img[usemap="#'+e+'"]')}var f=c[0].getBoundingClientRect(),g=a(h.window.document),i=a(h.window),j=c,k={available:{document:null,window:null},document:{size:{height:g.height(),width:g.width()}},window:{scroll:{left:h.window.scrollX||h.window.document.documentElement.scrollLeft,top:h.window.scrollY||h.window.document.documentElement.scrollTop},size:{height:i.height(),width:i.width()}},origin:{fixedLineage:!1,offset:{},size:{height:f.bottom-f.top,width:f.right-f.left},usemapImage:d?c[0]:null,windowOffset:{bottom:f.bottom,left:f.left,right:f.right,top:f.top}}};if(d){var l=b._$origin.attr("shape"),m=b._$origin.attr("coords");if(m&&(m=m.split(","),a.map(m,function(a,b){m[b]=parseInt(a)})),"default"!=l)switch(l){case"circle":var n=m[0],o=m[1],p=m[2],q=o-p,r=n-p;k.origin.size.height=2*p,k.origin.size.width=k.origin.size.height,k.origin.windowOffset.left+=r,k.origin.windowOffset.top+=q;break;case"rect":var s=m[0],t=m[1],u=m[2],v=m[3];k.origin.size.height=v-t,k.origin.size.width=u-s,k.origin.windowOffset.left+=s,k.origin.windowOffset.top+=t;break;case"poly":for(var w=0,x=0,y=0,z=0,A="even",B=0;B<m.length;B++){var C=m[B];"even"==A?(C>y&&(y=C,0===B&&(w=y)),w>C&&(w=C),A="odd"):(C>z&&(z=C,1==B&&(x=z)),x>C&&(x=C),A="even")}k.origin.size.height=z-x,k.origin.size.width=y-w,k.origin.windowOffset.left+=w,k.origin.windowOffset.top+=x}}var D=function(a){k.origin.size.height=a.height,k.origin.windowOffset.left=a.left,k.origin.windowOffset.top=a.top,k.origin.size.width=a.width};for(b._trigger({type:"geometry",edit:D,geometry:{height:k.origin.size.height,left:k.origin.windowOffset.left,top:k.origin.windowOffset.top,width:k.origin.size.width}}),k.origin.windowOffset.right=k.origin.windowOffset.left+k.origin.size.width,k.origin.windowOffset.bottom=k.origin.windowOffset.top+k.origin.size.height,k.origin.offset.left=k.origin.windowOffset.left+k.window.scroll.left,k.origin.offset.top=k.origin.windowOffset.top+k.window.scroll.top,k.origin.offset.bottom=k.origin.offset.top+k.origin.size.height,k.origin.offset.right=k.origin.offset.left+k.origin.size.width,k.available.document={bottom:{height:k.document.size.height-k.origin.offset.bottom,width:k.document.size.width},left:{height:k.document.size.height,width:k.origin.offset.left},right:{height:k.document.size.height,width:k.document.size.width-k.origin.offset.right},top:{height:k.origin.offset.top,width:k.document.size.width}},k.available.window={bottom:{height:Math.max(k.window.size.height-Math.max(k.origin.windowOffset.bottom,0),0),width:k.window.size.width},left:{height:k.window.size.height,width:Math.max(k.origin.windowOffset.left,0)},right:{height:k.window.size.height,width:Math.max(k.window.size.width-Math.max(k.origin.windowOffset.right,0),0)},top:{height:Math.max(k.origin.windowOffset.top,0),width:k.window.size.width}};"html"!=j[0].tagName.toLowerCase();){if("fixed"==j.css("position")){k.origin.fixedLineage=!0;break}j=j.parent()}return k},__optionsFormat:function(){return"number"==typeof this.__options.animationDuration&&(this.__options.animationDuration=[this.__options.animationDuration,this.__options.animationDuration]),"number"==typeof this.__options.delay&&(this.__options.delay=[this.__options.delay,this.__options.delay]),"number"==typeof this.__options.delayTouch&&(this.__options.delayTouch=[this.__options.delayTouch,this.__options.delayTouch]),"string"==typeof this.__options.theme&&(this.__options.theme=[this.__options.theme]),null===this.__options.parent?this.__options.parent=a(h.window.document.body):"string"==typeof this.__options.parent&&(this.__options.parent=a(this.__options.parent)),"hover"==this.__options.trigger?(this.__options.triggerOpen={mouseenter:!0,touchstart:!0},this.__options.triggerClose={mouseleave:!0,originClick:!0,touchleave:!0}):"click"==this.__options.trigger&&(this.__options.triggerOpen={click:!0,tap:!0},this.__options.triggerClose={click:!0,tap:!0}),this._trigger("options"),this},__prepareGC:function(){var b=this;return b.__options.selfDestruction?b.__garbageCollector=setInterval(function(){var c=(new Date).getTime();b.__touchEvents=a.grep(b.__touchEvents,function(a,b){return c-a.time>6e4}),d(b._$origin)||b.close(function(){b.destroy()})},2e4):clearInterval(b.__garbageCollector),b},__prepareOrigin:function(){var a=this;if(a._$origin.off("."+a.__namespace+"-triggerOpen"),h.hasTouchCapability&&a._$origin.on("touchstart."+a.__namespace+"-triggerOpen touchend."+a.__namespace+"-triggerOpen touchcancel."+a.__namespace+"-triggerOpen",function(b){a._touchRecordEvent(b)}),a.__options.triggerOpen.click||a.__options.triggerOpen.tap&&h.hasTouchCapability){var b="";a.__options.triggerOpen.click&&(b+="click."+a.__namespace+"-triggerOpen "),a.__options.triggerOpen.tap&&h.hasTouchCapability&&(b+="touchend."+a.__namespace+"-triggerOpen"),a._$origin.on(b,function(b){a._touchIsMeaningfulEvent(b)&&a._open(b)})}if(a.__options.triggerOpen.mouseenter||a.__options.triggerOpen.touchstart&&h.hasTouchCapability){var b="";a.__options.triggerOpen.mouseenter&&(b+="mouseenter."+a.__namespace+"-triggerOpen "),a.__options.triggerOpen.touchstart&&h.hasTouchCapability&&(b+="touchstart."+a.__namespace+"-triggerOpen"),a._$origin.on(b,function(b){!a._touchIsTouchEvent(b)&&a._touchIsEmulatedEvent(b)||(a.__pointerIsOverOrigin=!0,a._openShortly(b))})}if(a.__options.triggerClose.mouseleave||a.__options.triggerClose.touchleave&&h.hasTouchCapability){var b="";a.__options.triggerClose.mouseleave&&(b+="mouseleave."+a.__namespace+"-triggerOpen "),a.__options.triggerClose.touchleave&&h.hasTouchCapability&&(b+="touchend."+a.__namespace+"-triggerOpen touchcancel."+a.__namespace+"-triggerOpen"),a._$origin.on(b,function(b){a._touchIsMeaningfulEvent(b)&&(a.__pointerIsOverOrigin=!1)})}return a},__prepareTooltip:function(){var b=this,c=b.__options.interactive?"auto":"";return b._$tooltip.attr("id",b.__namespace).css({"pointer-events":c,zIndex:b.__options.zIndex}),a.each(b.__previousThemes,function(a,c){b._$tooltip.removeClass(c)}),a.each(b.__options.theme,function(a,c){b._$tooltip.addClass(c)}),b.__previousThemes=a.merge([],b.__options.theme),b},__scrollHandler:function(b){var c=this;if(c.__options.triggerClose.scroll)c._close(b);else if(d(c._$origin)&&d(c._$tooltip)){var e=null;if(b.target===h.window.document)c.__Geometry.origin.fixedLineage||c.__options.repositionOnScroll&&c.reposition(b);else{e=c.__geometry();var f=!1;if("fixed"!=c._$origin.css("position")&&c.__$originParents.each(function(b,c){var d=a(c),g=d.css("overflow-x"),h=d.css("overflow-y");if("visible"!=g||"visible"!=h){var i=c.getBoundingClientRect();if("visible"!=g&&(e.origin.windowOffset.left<i.left||e.origin.windowOffset.right>i.right))return f=!0,!1;if("visible"!=h&&(e.origin.windowOffset.top<i.top||e.origin.windowOffset.bottom>i.bottom))return f=!0,!1}return"fixed"==d.css("position")?!1:void 0}),f)c._$tooltip.css("visibility","hidden");else if(c._$tooltip.css("visibility","visible"),c.__options.repositionOnScroll)c.reposition(b);else{var g=e.origin.offset.left-c.__Geometry.origin.offset.left,i=e.origin.offset.top-c.__Geometry.origin.offset.top;c._$tooltip.css({left:c.__lastPosition.coord.left+g,top:c.__lastPosition.coord.top+i})}}c._trigger({type:"scroll",event:b,geo:e})}return c},__stateSet:function(a){return this.__state=a,this._trigger({type:"state",state:a}),this},__timeoutsClear:function(){return clearTimeout(this.__timeouts.open),this.__timeouts.open=null,a.each(this.__timeouts.close,function(a,b){clearTimeout(b)}),this.__timeouts.close=[],this},__trackerStart:function(){var a=this,b=a._$tooltip.find(".tooltipster-content");return a.__options.trackTooltip&&(a.__contentBcr=b[0].getBoundingClientRect()),a.__tracker=setInterval(function(){if(d(a._$origin)&&d(a._$tooltip)){if(a.__options.trackOrigin){var e=a.__geometry(),f=!1;c(e.origin.size,a.__Geometry.origin.size)&&(a.__Geometry.origin.fixedLineage?c(e.origin.windowOffset,a.__Geometry.origin.windowOffset)&&(f=!0):c(e.origin.offset,a.__Geometry.origin.offset)&&(f=!0)),f||(a.__options.triggerClose.mouseleave?a._close():a.reposition())}if(a.__options.trackTooltip){var g=b[0].getBoundingClientRect();g.height===a.__contentBcr.height&&g.width===a.__contentBcr.width||(a.reposition(),a.__contentBcr=g)}}else a._close()},a.__options.trackerInterval),a},_close:function(b,c,d){var e=this,f=!0;if(e._trigger({type:"close",event:b,stop:function(){f=!1}}),f||d){c&&e.__callbacks.close.push(c),e.__callbacks.open=[],e.__timeoutsClear();var g=function(){a.each(e.__callbacks.close,function(a,c){c.call(e,e,{event:b,origin:e._$origin[0]})}),e.__callbacks.close=[]};if("closed"!=e.__state){var i=!0,j=new Date,k=j.getTime(),l=k+e.__options.animationDuration[1];if("disappearing"==e.__state&&l>e.__closingTime&&e.__options.animationDuration[1]>0&&(i=!1),i){e.__closingTime=l,"disappearing"!=e.__state&&e.__stateSet("disappearing");var m=function(){clearInterval(e.__tracker),e._trigger({type:"closing",event:b}),e._$tooltip.off("."+e.__namespace+"-triggerClose").removeClass("tooltipster-dying"),a(h.window).off("."+e.__namespace+"-triggerClose"),e.__$originParents.each(function(b,c){a(c).off("scroll."+e.__namespace+"-triggerClose")}),e.__$originParents=null,a(h.window.document.body).off("."+e.__namespace+"-triggerClose"),e._$origin.off("."+e.__namespace+"-triggerClose"),e._off("dismissable"),e.__stateSet("closed"),e._trigger({type:"after",event:b}),e.__options.functionAfter&&e.__options.functionAfter.call(e,e,{event:b,origin:e._$origin[0]}),g()};h.hasTransitions?(e._$tooltip.css({"-moz-animation-duration":e.__options.animationDuration[1]+"ms","-ms-animation-duration":e.__options.animationDuration[1]+"ms","-o-animation-duration":e.__options.animationDuration[1]+"ms","-webkit-animation-duration":e.__options.animationDuration[1]+"ms","animation-duration":e.__options.animationDuration[1]+"ms","transition-duration":e.__options.animationDuration[1]+"ms"}),e._$tooltip.clearQueue().removeClass("tooltipster-show").addClass("tooltipster-dying"),e.__options.animationDuration[1]>0&&e._$tooltip.delay(e.__options.animationDuration[1]),e._$tooltip.queue(m)):e._$tooltip.stop().fadeOut(e.__options.animationDuration[1],m)}}else g()}return e},_off:function(){return this.__$emitterPrivate.off.apply(this.__$emitterPrivate,Array.prototype.slice.apply(arguments)),this},_on:function(){return this.__$emitterPrivate.on.apply(this.__$emitterPrivate,Array.prototype.slice.apply(arguments)),this},_one:function(){return this.__$emitterPrivate.one.apply(this.__$emitterPrivate,Array.prototype.slice.apply(arguments)),this},_open:function(b,c){var e=this;if(!e.__destroying&&d(e._$origin)&&e.__enabled){var f=!0;if("closed"==e.__state&&(e._trigger({type:"before",event:b,stop:function(){f=!1}}),f&&e.__options.functionBefore&&(f=e.__options.functionBefore.call(e,e,{event:b,origin:e._$origin[0]}))),f!==!1&&null!==e.__Content){c&&e.__callbacks.open.push(c),e.__callbacks.close=[],e.__timeoutsClear();var g,i=function(){"stable"!=e.__state&&e.__stateSet("stable"),a.each(e.__callbacks.open,function(a,b){b.call(e,e,{origin:e._$origin[0],tooltip:e._$tooltip[0]})}),e.__callbacks.open=[]};if("closed"!==e.__state)g=0,"disappearing"===e.__state?(e.__stateSet("appearing"),h.hasTransitions?(e._$tooltip.clearQueue().removeClass("tooltipster-dying").addClass("tooltipster-show"),e.__options.animationDuration[0]>0&&e._$tooltip.delay(e.__options.animationDuration[0]),e._$tooltip.queue(i)):e._$tooltip.stop().fadeIn(i)):"stable"==e.__state&&i();else{if(e.__stateSet("appearing"),g=e.__options.animationDuration[0],e.__contentInsert(),e.reposition(b,!0),h.hasTransitions?(e._$tooltip.addClass("tooltipster-"+e.__options.animation).addClass("tooltipster-initial").css({"-moz-animation-duration":e.__options.animationDuration[0]+"ms","-ms-animation-duration":e.__options.animationDuration[0]+"ms","-o-animation-duration":e.__options.animationDuration[0]+"ms","-webkit-animation-duration":e.__options.animationDuration[0]+"ms","animation-duration":e.__options.animationDuration[0]+"ms","transition-duration":e.__options.animationDuration[0]+"ms"}),setTimeout(function(){"closed"!=e.__state&&(e._$tooltip.addClass("tooltipster-show").removeClass("tooltipster-initial"),e.__options.animationDuration[0]>0&&e._$tooltip.delay(e.__options.animationDuration[0]),e._$tooltip.queue(i))},0)):e._$tooltip.css("display","none").fadeIn(e.__options.animationDuration[0],i),e.__trackerStart(),a(h.window).on("resize."+e.__namespace+"-triggerClose",function(b){var c=a(document.activeElement);(c.is("input")||c.is("textarea"))&&a.contains(e._$tooltip[0],c[0])||e.reposition(b)}).on("scroll."+e.__namespace+"-triggerClose",function(a){e.__scrollHandler(a)}),e.__$originParents=e._$origin.parents(),e.__$originParents.each(function(b,c){a(c).on("scroll."+e.__namespace+"-triggerClose",function(a){e.__scrollHandler(a)})}),e.__options.triggerClose.mouseleave||e.__options.triggerClose.touchleave&&h.hasTouchCapability){e._on("dismissable",function(a){a.dismissable?a.delay?(m=setTimeout(function(){e._close(a.event)},a.delay),e.__timeouts.close.push(m)):e._close(a):clearTimeout(m)});var j=e._$origin,k="",l="",m=null;e.__options.interactive&&(j=j.add(e._$tooltip)),e.__options.triggerClose.mouseleave&&(k+="mouseenter."+e.__namespace+"-triggerClose ",l+="mouseleave."+e.__namespace+"-triggerClose "),e.__options.triggerClose.touchleave&&h.hasTouchCapability&&(k+="touchstart."+e.__namespace+"-triggerClose",l+="touchend."+e.__namespace+"-triggerClose touchcancel."+e.__namespace+"-triggerClose"),j.on(l,function(a){if(e._touchIsTouchEvent(a)||!e._touchIsEmulatedEvent(a)){var b="mouseleave"==a.type?e.__options.delay:e.__options.delayTouch;e._trigger({delay:b[1],dismissable:!0,event:a,type:"dismissable"})}}).on(k,function(a){!e._touchIsTouchEvent(a)&&e._touchIsEmulatedEvent(a)||e._trigger({dismissable:!1,event:a,type:"dismissable"})})}e.__options.triggerClose.originClick&&e._$origin.on("click."+e.__namespace+"-triggerClose",function(a){e._touchIsTouchEvent(a)||e._touchIsEmulatedEvent(a)||e._close(a)}),(e.__options.triggerClose.click||e.__options.triggerClose.tap&&h.hasTouchCapability)&&setTimeout(function(){if("closed"!=e.__state){var b="",c=a(h.window.document.body);e.__options.triggerClose.click&&(b+="click."+e.__namespace+"-triggerClose "),e.__options.triggerClose.tap&&h.hasTouchCapability&&(b+="touchend."+e.__namespace+"-triggerClose"),c.on(b,function(b){e._touchIsMeaningfulEvent(b)&&(e._touchRecordEvent(b),e.__options.interactive&&a.contains(e._$tooltip[0],b.target)||e._close(b))}),e.__options.triggerClose.tap&&h.hasTouchCapability&&c.on("touchstart."+e.__namespace+"-triggerClose",function(a){e._touchRecordEvent(a)})}},0),e._trigger("ready"),e.__options.functionReady&&e.__options.functionReady.call(e,e,{origin:e._$origin[0],tooltip:e._$tooltip[0]})}if(e.__options.timer>0){var m=setTimeout(function(){e._close()},e.__options.timer+g);e.__timeouts.close.push(m)}}}return e},_openShortly:function(a){var b=this,c=!0;if("stable"!=b.__state&&"appearing"!=b.__state&&!b.__timeouts.open&&(b._trigger({type:"start",event:a,stop:function(){c=!1}}),c)){var d=0==a.type.indexOf("touch")?b.__options.delayTouch:b.__options.delay;d[0]?b.__timeouts.open=setTimeout(function(){b.__timeouts.open=null,b.__pointerIsOverOrigin&&b._touchIsMeaningfulEvent(a)?(b._trigger("startend"),b._open(a)):b._trigger("startcancel")},d[0]):(b._trigger("startend"),b._open(a))}return b},_optionsExtract:function(b,c){var d=this,e=a.extend(!0,{},c),f=d.__options[b];return f||(f={},a.each(c,function(a,b){var c=d.__options[a];void 0!==c&&(f[a]=c)})),a.each(e,function(b,c){void 0!==f[b]&&("object"!=typeof c||c instanceof Array||null==c||"object"!=typeof f[b]||f[b]instanceof Array||null==f[b]?e[b]=f[b]:a.extend(e[b],f[b]))}),e},_plug:function(b){var c=a.tooltipster._plugin(b);if(!c)throw new Error('The "'+b+'" plugin is not defined');return c.instance&&a.tooltipster.__bridge(c.instance,this,c.name),this},_touchIsEmulatedEvent:function(a){for(var b=!1,c=(new Date).getTime(),d=this.__touchEvents.length-1;d>=0;d--){var e=this.__touchEvents[d];if(!(c-e.time<500))break;e.target===a.target&&(b=!0)}return b},_touchIsMeaningfulEvent:function(a){return this._touchIsTouchEvent(a)&&!this._touchSwiped(a.target)||!this._touchIsTouchEvent(a)&&!this._touchIsEmulatedEvent(a)},_touchIsTouchEvent:function(a){return 0==a.type.indexOf("touch")},_touchRecordEvent:function(a){return this._touchIsTouchEvent(a)&&(a.time=(new Date).getTime(),this.__touchEvents.push(a)),this},_touchSwiped:function(a){for(var b=!1,c=this.__touchEvents.length-1;c>=0;c--){var d=this.__touchEvents[c];if("touchmove"==d.type){b=!0;break}if("touchstart"==d.type&&a===d.target)break}return b},_trigger:function(){var b=Array.prototype.slice.apply(arguments);return"string"==typeof b[0]&&(b[0]={type:b[0]}),b[0].instance=this,b[0].origin=this._$origin?this._$origin[0]:null,b[0].tooltip=this._$tooltip?this._$tooltip[0]:null,this.__$emitterPrivate.trigger.apply(this.__$emitterPrivate,b),a.tooltipster._trigger.apply(a.tooltipster,b),this.__$emitterPublic.trigger.apply(this.__$emitterPublic,b),this},_unplug:function(b){var c=this;if(c[b]){var d=a.tooltipster._plugin(b);d.instance&&a.each(d.instance,function(a,d){c[a]&&c[a].bridged===c[b]&&delete c[a]}),c[b].__destroy&&c[b].__destroy(),delete c[b]}return c},close:function(a){return this.__destroyed?this.__destroyError():this._close(null,a),this},content:function(a){var b=this;if(void 0===a)return b.__Content;if(b.__destroyed)b.__destroyError();else if(b.__contentSet(a),null!==b.__Content){if("closed"!==b.__state&&(b.__contentInsert(),b.reposition(),b.__options.updateAnimation))if(h.hasTransitions){var c=b.__options.updateAnimation;b._$tooltip.addClass("tooltipster-update-"+c),setTimeout(function(){"closed"!=b.__state&&b._$tooltip.removeClass("tooltipster-update-"+c)},1e3)}else b._$tooltip.fadeTo(200,.5,function(){"closed"!=b.__state&&b._$tooltip.fadeTo(200,1)})}else b._close();return b},destroy:function(){var b=this;if(b.__destroyed)b.__destroyError();else{"closed"!=b.__state?b.option("animationDuration",0)._close(null,null,!0):b.__timeoutsClear(),b._trigger("destroy"),b.__destroyed=!0,b._$origin.removeData(b.__namespace).off("."+b.__namespace+"-triggerOpen"),a(h.window.document.body).off("."+b.__namespace+"-triggerOpen");var c=b._$origin.data("tooltipster-ns");if(c)if(1===c.length){var d=null;"previous"==b.__options.restoration?d=b._$origin.data("tooltipster-initialTitle"):"current"==b.__options.restoration&&(d="string"==typeof b.__Content?b.__Content:a("<div></div>").append(b.__Content).html()),d&&b._$origin.attr("title",d),b._$origin.removeClass("tooltipstered"),b._$origin.removeData("tooltipster-ns").removeData("tooltipster-initialTitle")}else c=a.grep(c,function(a,c){return a!==b.__namespace}),b._$origin.data("tooltipster-ns",c);b._trigger("destroyed"),b._off(),b.off(),b.__Content=null,b.__$emitterPrivate=null,b.__$emitterPublic=null,b.__options.parent=null,b._$origin=null,b._$tooltip=null,a.tooltipster.__instancesLatestArr=a.grep(a.tooltipster.__instancesLatestArr,function(a,c){return b!==a}),clearInterval(b.__garbageCollector)}return b},disable:function(){return this.__destroyed?(this.__destroyError(),this):(this._close(),this.__enabled=!1,this)},elementOrigin:function(){return this.__destroyed?void this.__destroyError():this._$origin[0]},elementTooltip:function(){return this._$tooltip?this._$tooltip[0]:null},enable:function(){return this.__enabled=!0,this},hide:function(a){return this.close(a)},instance:function(){return this},off:function(){return this.__destroyed||this.__$emitterPublic.off.apply(this.__$emitterPublic,Array.prototype.slice.apply(arguments)),this},on:function(){return this.__destroyed?this.__destroyError():this.__$emitterPublic.on.apply(this.__$emitterPublic,Array.prototype.slice.apply(arguments)),this},one:function(){return this.__destroyed?this.__destroyError():this.__$emitterPublic.one.apply(this.__$emitterPublic,Array.prototype.slice.apply(arguments)),this},open:function(a){return this.__destroyed?this.__destroyError():this._open(null,a),this},option:function(b,c){return void 0===c?this.__options[b]:(this.__destroyed?this.__destroyError():(this.__options[b]=c,this.__optionsFormat(),a.inArray(b,["trigger","triggerClose","triggerOpen"])>=0&&this.__prepareOrigin(),"selfDestruction"===b&&this.__prepareGC()),this)},reposition:function(a,b){var c=this;return c.__destroyed?c.__destroyError():"closed"!=c.__state&&d(c._$origin)&&(b||d(c._$tooltip))&&(b||c._$tooltip.detach(),c.__Geometry=c.__geometry(),c._trigger({type:"reposition",event:a,helper:{geo:c.__Geometry}})),c},show:function(a){return this.open(a)},status:function(){return{destroyed:this.__destroyed,enabled:this.__enabled,open:"closed"!==this.__state,state:this.__state}},triggerHandler:function(){return this.__destroyed?this.__destroyError():this.__$emitterPublic.triggerHandler.apply(this.__$emitterPublic,Array.prototype.slice.apply(arguments)),this}},a.fn.tooltipster=function(){var b=Array.prototype.slice.apply(arguments),c="You are using a single HTML element as content for several tooltips. You probably want to set the contentCloning option to TRUE.";if(0===this.length)return this;if("string"==typeof b[0]){var d="#*$~&";return this.each(function(){var e=a(this).data("tooltipster-ns"),f=e?a(this).data(e[0]):null;if(!f)throw new Error("You called Tooltipster's \""+b[0]+'" method on an uninitialized element');if("function"!=typeof f[b[0]])throw new Error('Unknown method "'+b[0]+'"');this.length>1&&"content"==b[0]&&(b[1]instanceof a||"object"==typeof b[1]&&null!=b[1]&&b[1].tagName)&&!f.__options.contentCloning&&f.__options.debug&&console.log(c);var g=f[b[0]](b[1],b[2]);return g!==f||"instance"===b[0]?(d=g,!1):void 0}),"#*$~&"!==d?d:this}a.tooltipster.__instancesLatestArr=[];var e=b[0]&&void 0!==b[0].multiple,g=e&&b[0].multiple||!e&&f.multiple,h=b[0]&&void 0!==b[0].content,i=h&&b[0].content||!h&&f.content,j=b[0]&&void 0!==b[0].contentCloning,k=j&&b[0].contentCloning||!j&&f.contentCloning,l=b[0]&&void 0!==b[0].debug,m=l&&b[0].debug||!l&&f.debug;return this.length>1&&(i instanceof a||"object"==typeof i&&null!=i&&i.tagName)&&!k&&m&&console.log(c),this.each(function(){var c=!1,d=a(this),e=d.data("tooltipster-ns"),f=null;e?g?c=!0:m&&(console.log("Tooltipster: one or more tooltips are already attached to the element below. Ignoring."),console.log(this)):c=!0,c&&(f=new a.Tooltipster(this,b[0]),e||(e=[]),e.push(f.__namespace),d.data("tooltipster-ns",e),d.data(f.__namespace,f),f.__options.functionInit&&f.__options.functionInit.call(f,f,{origin:this}),f._trigger("init")),a.tooltipster.__instancesLatestArr.push(f)}),this},b.prototype={__init:function(b){this.__$tooltip=b,this.__$tooltip.css({left:0,overflow:"hidden",position:"absolute",top:0}).find(".tooltipster-content").css("overflow","auto"),this.$container=a('<div class="tooltipster-ruler"></div>').append(this.__$tooltip).appendTo(h.window.document.body)},__forceRedraw:function(){var a=this.__$tooltip.parent();this.__$tooltip.detach(),this.__$tooltip.appendTo(a)},constrain:function(a,b){return this.constraints={width:a,height:b},this.__$tooltip.css({display:"block",height:"",overflow:"auto",width:a}),this},destroy:function(){this.__$tooltip.detach().find(".tooltipster-content").css({display:"",overflow:""}),this.$container.remove()},free:function(){return this.constraints=null,this.__$tooltip.css({display:"",height:"",overflow:"visible",width:""}),this},measure:function(){this.__forceRedraw();var a=this.__$tooltip[0].getBoundingClientRect(),b={size:{height:a.height||a.bottom-a.top,width:a.width||a.right-a.left}};if(this.constraints){var c=this.__$tooltip.find(".tooltipster-content"),d=this.__$tooltip.outerHeight(),e=c[0].getBoundingClientRect(),f={height:d<=this.constraints.height,width:a.width<=this.constraints.width&&e.width>=c[0].scrollWidth-1};b.fits=f.height&&f.width}return h.IE&&h.IE<=11&&b.size.width!==h.window.document.documentElement.clientWidth&&(b.size.width=Math.ceil(b.size.width)+1),b}};var j=navigator.userAgent.toLowerCase();-1!=j.indexOf("msie")?h.IE=parseInt(j.split("msie")[1]):-1!==j.toLowerCase().indexOf("trident")&&-1!==j.indexOf(" rv:11")?h.IE=11:-1!=j.toLowerCase().indexOf("edge/")&&(h.IE=parseInt(j.toLowerCase().split("edge/")[1]));var k="tooltipster.sideTip";return a.tooltipster._plugin({name:k,instance:{__defaults:function(){return{arrow:!0,distance:6,functionPosition:null,maxWidth:null,minIntersection:16,minWidth:0,position:null,side:"top",viewportAware:!0}},__init:function(a){var b=this;b.__instance=a,b.__namespace="tooltipster-sideTip-"+Math.round(1e6*Math.random()),b.__previousState="closed",b.__options,b.__optionsFormat(),b.__instance._on("state."+b.__namespace,function(a){"closed"==a.state?b.__close():"appearing"==a.state&&"closed"==b.__previousState&&b.__create(),b.__previousState=a.state}),b.__instance._on("options."+b.__namespace,function(){b.__optionsFormat()}),b.__instance._on("reposition."+b.__namespace,function(a){b.__reposition(a.event,a.helper)})},__close:function(){this.__instance.content()instanceof a&&this.__instance.content().detach(),this.__instance._$tooltip.remove(),this.__instance._$tooltip=null},__create:function(){var b=a('<div class="tooltipster-base tooltipster-sidetip"><div class="tooltipster-box"><div class="tooltipster-content"></div></div><div class="tooltipster-arrow"><div class="tooltipster-arrow-uncropped"><div class="tooltipster-arrow-border"></div><div class="tooltipster-arrow-background"></div></div></div></div>');this.__options.arrow||b.find(".tooltipster-box").css("margin",0).end().find(".tooltipster-arrow").hide(),this.__options.minWidth&&b.css("min-width",this.__options.minWidth+"px"),this.__options.maxWidth&&b.css("max-width",this.__options.maxWidth+"px"),
this.__instance._$tooltip=b,this.__instance._trigger("created")},__destroy:function(){this.__instance._off("."+self.__namespace)},__optionsFormat:function(){var b=this;if(b.__options=b.__instance._optionsExtract(k,b.__defaults()),b.__options.position&&(b.__options.side=b.__options.position),"object"!=typeof b.__options.distance&&(b.__options.distance=[b.__options.distance]),b.__options.distance.length<4&&(void 0===b.__options.distance[1]&&(b.__options.distance[1]=b.__options.distance[0]),void 0===b.__options.distance[2]&&(b.__options.distance[2]=b.__options.distance[0]),void 0===b.__options.distance[3]&&(b.__options.distance[3]=b.__options.distance[1]),b.__options.distance={top:b.__options.distance[0],right:b.__options.distance[1],bottom:b.__options.distance[2],left:b.__options.distance[3]}),"string"==typeof b.__options.side){var c={top:"bottom",right:"left",bottom:"top",left:"right"};b.__options.side=[b.__options.side,c[b.__options.side]],"left"==b.__options.side[0]||"right"==b.__options.side[0]?b.__options.side.push("top","bottom"):b.__options.side.push("right","left")}6===a.tooltipster._env.IE&&b.__options.arrow!==!0&&(b.__options.arrow=!1)},__reposition:function(b,c){var d,e=this,f=e.__targetFind(c),g=[];e.__instance._$tooltip.detach();var h=e.__instance._$tooltip.clone(),i=a.tooltipster._getRuler(h),j=!1,k=e.__instance.option("animation");switch(k&&h.removeClass("tooltipster-"+k),a.each(["window","document"],function(d,k){var l=null;if(e.__instance._trigger({container:k,helper:c,satisfied:j,takeTest:function(a){l=a},results:g,type:"positionTest"}),1==l||0!=l&&0==j&&("window"!=k||e.__options.viewportAware))for(var d=0;d<e.__options.side.length;d++){var m={horizontal:0,vertical:0},n=e.__options.side[d];"top"==n||"bottom"==n?m.vertical=e.__options.distance[n]:m.horizontal=e.__options.distance[n],e.__sideChange(h,n),a.each(["natural","constrained"],function(a,d){if(l=null,e.__instance._trigger({container:k,event:b,helper:c,mode:d,results:g,satisfied:j,side:n,takeTest:function(a){l=a},type:"positionTest"}),1==l||0!=l&&0==j){var h={container:k,distance:m,fits:null,mode:d,outerSize:null,side:n,size:null,target:f[n],whole:null},o="natural"==d?i.free():i.constrain(c.geo.available[k][n].width-m.horizontal,c.geo.available[k][n].height-m.vertical),p=o.measure();if(h.size=p.size,h.outerSize={height:p.size.height+m.vertical,width:p.size.width+m.horizontal},"natural"==d?c.geo.available[k][n].width>=h.outerSize.width&&c.geo.available[k][n].height>=h.outerSize.height?h.fits=!0:h.fits=!1:h.fits=p.fits,"window"==k&&(h.fits?"top"==n||"bottom"==n?h.whole=c.geo.origin.windowOffset.right>=e.__options.minIntersection&&c.geo.window.size.width-c.geo.origin.windowOffset.left>=e.__options.minIntersection:h.whole=c.geo.origin.windowOffset.bottom>=e.__options.minIntersection&&c.geo.window.size.height-c.geo.origin.windowOffset.top>=e.__options.minIntersection:h.whole=!1),g.push(h),h.whole)j=!0;else if("natural"==h.mode&&(h.fits||h.size.width<=c.geo.available[k][n].width))return!1}})}}),e.__instance._trigger({edit:function(a){g=a},event:b,helper:c,results:g,type:"positionTested"}),g.sort(function(a,b){if(a.whole&&!b.whole)return-1;if(!a.whole&&b.whole)return 1;if(a.whole&&b.whole){var c=e.__options.side.indexOf(a.side),d=e.__options.side.indexOf(b.side);return d>c?-1:c>d?1:"natural"==a.mode?-1:1}if(a.fits&&!b.fits)return-1;if(!a.fits&&b.fits)return 1;if(a.fits&&b.fits){var c=e.__options.side.indexOf(a.side),d=e.__options.side.indexOf(b.side);return d>c?-1:c>d?1:"natural"==a.mode?-1:1}return"document"==a.container&&"bottom"==a.side&&"natural"==a.mode?-1:1}),d=g[0],d.coord={},d.side){case"left":case"right":d.coord.top=Math.floor(d.target-d.size.height/2);break;case"bottom":case"top":d.coord.left=Math.floor(d.target-d.size.width/2)}switch(d.side){case"left":d.coord.left=c.geo.origin.windowOffset.left-d.outerSize.width;break;case"right":d.coord.left=c.geo.origin.windowOffset.right+d.distance.horizontal;break;case"top":d.coord.top=c.geo.origin.windowOffset.top-d.outerSize.height;break;case"bottom":d.coord.top=c.geo.origin.windowOffset.bottom+d.distance.vertical}"window"==d.container?"top"==d.side||"bottom"==d.side?d.coord.left<0?c.geo.origin.windowOffset.right-this.__options.minIntersection>=0?d.coord.left=0:d.coord.left=c.geo.origin.windowOffset.right-this.__options.minIntersection-1:d.coord.left>c.geo.window.size.width-d.size.width&&(c.geo.origin.windowOffset.left+this.__options.minIntersection<=c.geo.window.size.width?d.coord.left=c.geo.window.size.width-d.size.width:d.coord.left=c.geo.origin.windowOffset.left+this.__options.minIntersection+1-d.size.width):d.coord.top<0?c.geo.origin.windowOffset.bottom-this.__options.minIntersection>=0?d.coord.top=0:d.coord.top=c.geo.origin.windowOffset.bottom-this.__options.minIntersection-1:d.coord.top>c.geo.window.size.height-d.size.height&&(c.geo.origin.windowOffset.top+this.__options.minIntersection<=c.geo.window.size.height?d.coord.top=c.geo.window.size.height-d.size.height:d.coord.top=c.geo.origin.windowOffset.top+this.__options.minIntersection+1-d.size.height):(d.coord.left>c.geo.window.size.width-d.size.width&&(d.coord.left=c.geo.window.size.width-d.size.width),d.coord.left<0&&(d.coord.left=0)),e.__sideChange(h,d.side),c.tooltipClone=h[0],c.tooltipParent=e.__instance.option("parent").parent[0],c.mode=d.mode,c.whole=d.whole,c.origin=e.__instance._$origin[0],c.tooltip=e.__instance._$tooltip[0],delete d.container,delete d.fits,delete d.mode,delete d.outerSize,delete d.whole,d.distance=d.distance.horizontal||d.distance.vertical;var l=a.extend(!0,{},d);if(e.__instance._trigger({edit:function(a){d=a},event:b,helper:c,position:l,type:"position"}),e.__options.functionPosition){var m=e.__options.functionPosition.call(e,e.__instance,c,l);m&&(d=m)}i.destroy();var n,o;"top"==d.side||"bottom"==d.side?(n={prop:"left",val:d.target-d.coord.left},o=d.size.width-this.__options.minIntersection):(n={prop:"top",val:d.target-d.coord.top},o=d.size.height-this.__options.minIntersection),n.val<this.__options.minIntersection?n.val=this.__options.minIntersection:n.val>o&&(n.val=o);var p;p=c.geo.origin.fixedLineage?c.geo.origin.windowOffset:{left:c.geo.origin.windowOffset.left+c.geo.window.scroll.left,top:c.geo.origin.windowOffset.top+c.geo.window.scroll.top},d.coord={left:p.left+(d.coord.left-c.geo.origin.windowOffset.left),top:p.top+(d.coord.top-c.geo.origin.windowOffset.top)},e.__sideChange(e.__instance._$tooltip,d.side),c.geo.origin.fixedLineage?e.__instance._$tooltip.css("position","fixed"):e.__instance._$tooltip.css("position",""),e.__instance._$tooltip.css({left:d.coord.left,top:d.coord.top,height:d.size.height,width:d.size.width}).find(".tooltipster-arrow").css({left:"",top:""}).css(n.prop,n.val),e.__instance._$tooltip.appendTo(e.__instance.option("parent")),e.__instance._trigger({type:"repositioned",event:b,position:d})},__sideChange:function(a,b){a.removeClass("tooltipster-bottom").removeClass("tooltipster-left").removeClass("tooltipster-right").removeClass("tooltipster-top").addClass("tooltipster-"+b)},__targetFind:function(a){var b={},c=this.__instance._$origin[0].getClientRects();if(c.length>1){var d=this.__instance._$origin.css("opacity");1==d&&(this.__instance._$origin.css("opacity",.99),c=this.__instance._$origin[0].getClientRects(),this.__instance._$origin.css("opacity",1))}if(c.length<2)b.top=Math.floor(a.geo.origin.windowOffset.left+a.geo.origin.size.width/2),b.bottom=b.top,b.left=Math.floor(a.geo.origin.windowOffset.top+a.geo.origin.size.height/2),b.right=b.left;else{var e=c[0];b.top=Math.floor(e.left+(e.right-e.left)/2),e=c.length>2?c[Math.ceil(c.length/2)-1]:c[0],b.right=Math.floor(e.top+(e.bottom-e.top)/2),e=c[c.length-1],b.bottom=Math.floor(e.left+(e.right-e.left)/2),e=c.length>2?c[Math.ceil((c.length+1)/2)-1]:c[c.length-1],b.left=Math.floor(e.top+(e.bottom-e.top)/2)}return b}}}),a});
/**
* simplePagination.js v1.6
* A simple jQuery pagination plugin.
* http://flaviusmatis.github.com/simplePagination.js/
*
* Copyright 2012, Flavius Matis
* Released under the MIT license.
* http://flaviusmatis.github.com/license.html
*/

(function($){

	var methods = {
		init: function(options) {
			var o = $.extend({
				items: 1,
				itemsOnPage: 1,
				pages: 0,
				displayedPages: 5,
				edges: 2,
				currentPage: 0,
				useAnchors: true,
				hrefTextPrefix: '#page-',
				hrefTextSuffix: '',
				prevText: 'Prev',
				nextText: 'Next',
				ellipseText: '&hellip;',
				ellipsePageSet: true,
				cssStyle: 'light-theme',
				listStyle: '',
				labelMap: [],
				selectOnClick: true,
				nextAtFront: false,
				invertPageOrder: false,
				useStartEdge : true,
				useEndEdge : true,
				onPageClick: function(pageNumber, event) {
					// Callback triggered when a page is clicked
					// Page number is given as an optional parameter
				},
				onInit: function() {
					// Callback triggered immediately after initialization
				}
			}, options || {});

			var self = this;

			o.pages = o.pages ? o.pages : Math.ceil(o.items / o.itemsOnPage) ? Math.ceil(o.items / o.itemsOnPage) : 1;
			if (o.currentPage)
				o.currentPage = o.currentPage - 1;
			else
				o.currentPage = !o.invertPageOrder ? 0 : o.pages - 1;
			o.halfDisplayed = o.displayedPages / 2;

			this.each(function() {
				self.addClass(o.cssStyle + ' simple-pagination').data('pagination', o);
				methods._draw.call(self);
			});

			o.onInit();

			return this;
		},

		selectPage: function(page) {
			methods._selectPage.call(this, page - 1);
			return this;
		},

		prevPage: function() {
			var o = this.data('pagination');
			if (!o.invertPageOrder) {
				if (o.currentPage > 0) {
					methods._selectPage.call(this, o.currentPage - 1);
				}
			} else {
				if (o.currentPage < o.pages - 1) {
					methods._selectPage.call(this, o.currentPage + 1);
				}
			}
			return this;
		},

		nextPage: function() {
			var o = this.data('pagination');
			if (!o.invertPageOrder) {
				if (o.currentPage < o.pages - 1) {
					methods._selectPage.call(this, o.currentPage + 1);
				}
			} else {
				if (o.currentPage > 0) {
					methods._selectPage.call(this, o.currentPage - 1);
				}
			}
			return this;
		},

		getPagesCount: function() {
			return this.data('pagination').pages;
		},

		setPagesCount: function(count) {
			this.data('pagination').pages = count;
		},

		getCurrentPage: function () {
			return this.data('pagination').currentPage + 1;
		},

		destroy: function(){
			this.empty();
			return this;
		},

		drawPage: function (page) {
			var o = this.data('pagination');
			o.currentPage = page - 1;
			this.data('pagination', o);
			methods._draw.call(this);
			return this;
		},

		redraw: function(){
			methods._draw.call(this);
			return this;
		},

		disable: function(){
			var o = this.data('pagination');
			o.disabled = true;
			this.data('pagination', o);
			methods._draw.call(this);
			return this;
		},

		enable: function(){
			var o = this.data('pagination');
			o.disabled = false;
			this.data('pagination', o);
			methods._draw.call(this);
			return this;
		},

		updateItems: function (newItems) {
			var o = this.data('pagination');
			o.items = newItems;
			o.pages = methods._getPages(o);
			this.data('pagination', o);
			methods._draw.call(this);
		},

		updateItemsOnPage: function (itemsOnPage) {
			var o = this.data('pagination');
			o.itemsOnPage = itemsOnPage;
			o.pages = methods._getPages(o);
			this.data('pagination', o);
			methods._selectPage.call(this, 0);
			return this;
		},

		getItemsOnPage: function() {
			return this.data('pagination').itemsOnPage;
		},

		_draw: function() {
			var	o = this.data('pagination'),
				interval = methods._getInterval(o),
				i,
				tagName;

			methods.destroy.call(this);

			tagName = (typeof this.prop === 'function') ? this.prop('tagName') : this.attr('tagName');

			var $panel = tagName === 'UL' ? this : $('<ul' + (o.listStyle ? ' class="' + o.listStyle + '"' : '') + '></ul>').appendTo(this);

			// Generate Prev link
			if (o.prevText) {
				methods._appendItem.call(this, !o.invertPageOrder ? o.currentPage - 1 : o.currentPage + 1, {text: o.prevText, classes: 'prev'});
			}

			// Generate Next link (if option set for at front)
			if (o.nextText && o.nextAtFront) {
				methods._appendItem.call(this, !o.invertPageOrder ? o.currentPage + 1 : o.currentPage - 1, {text: o.nextText, classes: 'next'});
			}

			// Generate start edges
			if (!o.invertPageOrder) {
				if (interval.start > 0 && o.edges > 0) {
					if(o.useStartEdge) {
						var end = Math.min(o.edges, interval.start);
						for (i = 0; i < end; i++) {
							methods._appendItem.call(this, i);
						}
					}
					if (o.edges < interval.start && (interval.start - o.edges != 1)) {
						$panel.append('<li class="disabled"><span class="ellipse">' + o.ellipseText + '</span></li>');
					} else if (interval.start - o.edges == 1) {
						methods._appendItem.call(this, o.edges);
					}
				}
			} else {
				if (interval.end < o.pages && o.edges > 0) {
					if(o.useStartEdge) {
						var begin = Math.max(o.pages - o.edges, interval.end);
						for (i = o.pages - 1; i >= begin; i--) {
							methods._appendItem.call(this, i);
						}
					}

					if (o.pages - o.edges > interval.end && (o.pages - o.edges - interval.end != 1)) {
						$panel.append('<li class="disabled"><span class="ellipse">' + o.ellipseText + '</span></li>');
					} else if (o.pages - o.edges - interval.end == 1) {
						methods._appendItem.call(this, interval.end);
					}
				}
			}

			// Generate interval links
			if (!o.invertPageOrder) {
				for (i = interval.start; i < interval.end; i++) {
					methods._appendItem.call(this, i);
				}
			} else {
				for (i = interval.end - 1; i >= interval.start; i--) {
					methods._appendItem.call(this, i);
				}
			}

			// Generate end edges
			if (!o.invertPageOrder) {
				if (interval.end < o.pages && o.edges > 0) {
					if (o.pages - o.edges > interval.end && (o.pages - o.edges - interval.end != 1)) {
						$panel.append('<li class="disabled"><span class="ellipse">' + o.ellipseText + '</span></li>');
					} else if (o.pages - o.edges - interval.end == 1) {
						methods._appendItem.call(this, interval.end);
					}
					if(o.useEndEdge) {
						var begin = Math.max(o.pages - o.edges, interval.end);
						for (i = begin; i < o.pages; i++) {
							methods._appendItem.call(this, i);
						}
					}
				}
			} else {
				if (interval.start > 0 && o.edges > 0) {
					if (o.edges < interval.start && (interval.start - o.edges != 1)) {
						$panel.append('<li class="disabled"><span class="ellipse">' + o.ellipseText + '</span></li>');
					} else if (interval.start - o.edges == 1) {
						methods._appendItem.call(this, o.edges);
					}

					if(o.useEndEdge) {
						var end = Math.min(o.edges, interval.start);
						for (i = end - 1; i >= 0; i--) {
							methods._appendItem.call(this, i);
						}
					}
				}
			}

			// Generate Next link (unless option is set for at front)
			if (o.nextText && !o.nextAtFront) {
				methods._appendItem.call(this, !o.invertPageOrder ? o.currentPage + 1 : o.currentPage - 1, {text: o.nextText, classes: 'next'});
			}

			if (o.ellipsePageSet && !o.disabled) {
				methods._ellipseClick.call(this, $panel);
			}

		},

		_getPages: function(o) {
			var pages = Math.ceil(o.items / o.itemsOnPage);
			return pages || 1;
		},

		_getInterval: function(o) {
			return {
				start: Math.ceil(o.currentPage > o.halfDisplayed ? Math.max(Math.min(o.currentPage - o.halfDisplayed, (o.pages - o.displayedPages)), 0) : 0),
				end: Math.ceil(o.currentPage > o.halfDisplayed ? Math.min(o.currentPage + o.halfDisplayed, o.pages) : Math.min(o.displayedPages, o.pages))
			};
		},

		_appendItem: function(pageIndex, opts) {
			var self = this, options, $link, o = self.data('pagination'), $linkWrapper = $('<li></li>'), $ul = self.find('ul');

			pageIndex = pageIndex < 0 ? 0 : (pageIndex < o.pages ? pageIndex : o.pages - 1);

			options = {
				text: pageIndex + 1,
				classes: ''
			};

			if (o.labelMap.length && o.labelMap[pageIndex]) {
				options.text = o.labelMap[pageIndex];
			}

			options = $.extend(options, opts || {});

			if (pageIndex == o.currentPage || o.disabled) {
				if (o.disabled || options.classes === 'prev' || options.classes === 'next') {
					$linkWrapper.addClass('disabled');
				} else {
					$linkWrapper.addClass('active');
				}
				$link = $('<span class="current">' + (options.text) + '</span>');
			} else {
                if (o.useAnchors) {
    
					//$link = $('<a href="' + o.hrefTextPrefix + (pageIndex + 1) + o.hrefTextSuffix + '" class="page-link">' + (options.text) + '</a>');
                    $link = $('<a href="#course-grid-header" class="page-link">' + (options.text) + '</a>');

				} else {
					$link = $('<span >' + (options.text) + '</span>');
				}
				$link.click(function(event){
					return methods._selectPage.call(self, pageIndex, event);
				});
			}

			if (options.classes) {
				$link.addClass(options.classes);
			}

			$linkWrapper.append($link);

			if ($ul.length) {
				$ul.append($linkWrapper);
			} else {
				self.append($linkWrapper);
			}
		},

		_selectPage: function(pageIndex, event) {
			var o = this.data('pagination');
			o.currentPage = pageIndex;
			if (o.selectOnClick) {
				methods._draw.call(this);
			}
			return o.onPageClick(pageIndex + 1, event);
		},


		_ellipseClick: function($panel) {
			var self = this,
				o = this.data('pagination'),
				$ellip = $panel.find('.ellipse');
			$ellip.addClass('clickable').parent().removeClass('disabled');
			$ellip.click(function(event) {
				if (!o.disable) {
					var $this = $(this),
						val = (parseInt($this.parent().prev().text(), 10) || 0) + 1;
					$this
						.html('<input type="number" min="1" max="' + o.pages + '" step="1" value="' + val + '">')
						.find('input')
						.focus()
						.click(function(event) {
							// prevent input number arrows from bubbling a click event on $ellip
							event.stopPropagation();
						})
						.keyup(function(event) {
							var val = $(this).val();
							if (event.which === 13 && val !== '') {
								// enter to accept
								if ((val>0)&&(val<=o.pages))
								methods._selectPage.call(self, val - 1);
							} else if (event.which === 27) {
								// escape to cancel
								$ellip.empty().html(o.ellipseText);
							}
						})
						.bind('blur', function(event) {
							var val = $(this).val();
							if (val !== '') {
								methods._selectPage.call(self, val - 1);
							}
							$ellip.empty().html(o.ellipseText);
							return false;
						});
				}
				return false;
			});
		}

	};

	$.fn.pagination = function(method) {

		// Method calling logic
		if (methods[method] && method.charAt(0) != '_') {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error('Method ' +  method + ' does not exist on jQuery.pagination');
		}

	};

})(jQuery);

// The function actually applying the offset
function offsetAnchor() {
    if (location.hash.length !== 0) {
        window.scrollTo(window.scrollX, window.scrollY - 100);
    }
}

// Captures click events of all <a> elements with href starting with #
$(document).on('click', 'a[href^="#"]', function (event) {
    // Click events are captured before hashchanges. Timeout
    // causes offsetAnchor to be called after the page jump.
    window.setTimeout(function () {
        offsetAnchor();
    }, 0);
});

//Ensure all boxes align with the tallest box
$(document).ready(function () {

    var elHelpAdvice = $('.help-advice-block .entry-content');
    var elArticle = $('.help-advice-block article');

    if (elHelpAdvice != null)
        setBlockHeight(elHelpAdvice);
    if (elArticle != null)
        setBlockHeight(elArticle);

    // Skip to Content
    var skipToContent = $('#skip-to-content');

    if (skipToContent == null || skipToContent.length < 1) {
        var headingsH1 = $('h1');
        var headingsH2 = $('h2');
        var firstHeading = null;

        if (headingsH1.length > 1) {
            firstHeading = headingsH1[0];
        }
        else if(headingsH2.length < 1)
        {
            firstHeading = headingsH2[0];
        }

        if (firstHeading != null) {
            firstHeading.id = 'skip-to-content';
        }
    }
});

function setBlockHeight(el) {
    let h = 0;
    for (let i = 0; i < el.length; i++) {
        console.log(el[i].clientHeight);

        if (el[i].clientHeight > h)
            h = el[i].clientHeight;
    }

    for (let i = 0; i < el.length; i++) {
        el[i].setAttribute("style", "min-height:" + h + "px");
    }
}
// Set the offset when entering page with hash present in the url
window.setTimeout(offsetAnchor, 0);
var isResizing = false;



//resize heading text
function resizeHeadingText(autoLoad) {
    var resizeHeadingTextLoad = null;

    if(resizeHeadingTextLoad === null && autoLoad) {
        resizeHeadingTextLoad = setInterval(function () { 
            var $text = document.getElementsByClassName('cornered-border-green');
            if($text.length > 0) {
                clearInterval(resizeHeadingTextLoad);
                resizeHeadingTextLoad = null;
                resizeHeadingTextProcess($text);
            }
            resizeHeadingText();
        }, 10)
    }    

    if(!autoLoad) {
        var $text = document.getElementsByClassName('cornered-border-green');
        if($text.length > 0) {
            resizeHeadingTextProcess($text);
        }
    }

}

function resizeHeadingTextProcess($text) {
    var $textArray = [].slice.call($text, 0);

    $textArray.map(function (item, key) {

        item.style.width = 'auto';
        item.style.height = 'auto';
        item.style.paddingLeft = '15px';
        item.style.paddingRight = '15px';

        setTimeout(function() {
            var t = item.querySelector('span');


            
            if(t) {
                var h = t.offsetHeight;

                if(isMobile() && h > 34) {
                    t.style.marginLeft = '-15px';
                    t.style.marginRight = '-15px';
                }
    
                var w = t.offsetWidth;
    
                t.style.marginLeft = '0px';
                t.style.marginRight = '0px';
                item.style.width = w + 'px';
                item.style.height = h + 'px';
                item.style.paddingLeft = '0px';
                item.style.paddingRight = '0px';
            }

        }, 10);
           
    })
}

function isMobile() {
    return window.innerWidth < 768;
}



//set height to featured modules 
function setHeightToFeturedModules(el, extra, checkifExtras) {

    if(!extra) {
        extra = 0;
    }

    if(!checkifExtras) {
        checkifExtras = false;
    }

    var heightLoad = null;
    if(heightLoad === null) {
        heightLoad = setInterval(function() {
            var $module = document.getElementsByClassName('mobile-scroll-container');
            if($module.length > 0) {
                clearInterval(heightLoad);
                procesHeightToFeturedModules($module, el, extra, checkifExtras)      
            }
           
        }, 10);
    }
    
}

function setHeightToFeturedModulesHeader(el) {
    var heightLoad = null;
    if(heightLoad === null) {
        heightLoad = setInterval(function() {
            var $module = document.getElementsByClassName('mobile-scroll-container');
            if($module.length > 0) {
                clearInterval(heightLoad);
                procesHeightToFeturedModulesHeader($module, el)      
            }
           
        }, 10);
    }
    
}

function procesHeightToFeturedModules($module, el, extra, checkifExtras) {
    heightLoad = null;

    var $modules = [].slice.call($module, 0)

    $modules.map(function(item, key) {
        var $slides = item.getElementsByClassName('module--featured-content');
        var $slidesArray = [].slice.call($slides, 0)
        var heights = [];
        var hasExtra = [];
        
        Promise.all(
            $slidesArray.map(function(i, k) {
        

                var $textBox = i.querySelector(el);
                $textBox.style.height = 'auto';

                if(checkifExtras) {
                    var $extraBox = i.querySelector('.course-price-container');

                    if($extraBox) {
                        hasExtra.push(true);
                    }
                }

                var h = $textBox.offsetHeight;
                
                // if(h === 0) {
                //     $textBox.innerHTML  = '<p>&nbsp;</p>'
                // }
                
                heights.push(h);
            })
            
        ).then(function() {
            var maxHeight =  heights.reduce(function(a, b) {
                return Math.max(a, b);
            });
        
            var processExtra = hasExtra.indexOf(true) !== -1;
    
            $slidesArray.map(function(i, k) {
                var $textBox = i.querySelector(el);
                var addExtra = 0;

                if(processExtra) {
                    addExtra = 70;
                }

                $textBox.style.height = maxHeight + extra + addExtra + 'px';
            })
        })
       
    })
}

function procesHeightToFeturedModulesHeader($module, el) {
    heightLoad = null;

    var $modules = [].slice.call($module, 0)

    $modules.map(function(item, key) {
        var $slides = item.getElementsByClassName('module--featured-content');
        var $slidesArray = [].slice.call($slides, 0)
        var heights = [];
        var hasExtra = [];
        
        Promise.all(
            $slidesArray.map(function(i, k) {
        

                var $textBox = i.querySelector(el);
                $textBox.style.height = 'auto';

              

                var h = $textBox.offsetHeight;
                
                // if(h === 0) {
                //     $textBox.innerHTML  = '<p>&nbsp;</p>'
                // }
                
                heights.push(h);
            })
            
        ).then(function() {
            var maxHeight =  heights.reduce(function(a, b) {
                return Math.max(a, b);
            });

            $slidesArray.map(function(i, k) {
                var $textBox = i.querySelector(el);
                var $textBoxInfo = i.querySelector('.summary-text-container');
                var $tbih = $textBoxInfo.offsetHeight;
                var ch = heights[k];

                if(maxHeight > ch) {
                    const dif = maxHeight - ch;
                    $textBoxInfo.style.height = $tbih + dif + 'px';
                }

                $textBox.style.height = ch + 'px';
            })
        })
       
    })
}

window.procesHeightToFeturedModules = procesHeightToFeturedModules;
window.procesHeightToFeturedModulesHeader = procesHeightToFeturedModulesHeader;


function setHeightToModules() {
    setHeightToFeturedModules('.featured-image');
    setHeightToFeturedModules('.summary-text-container', 75, true);
    setHeightToFeturedModulesHeader('.header-text-container');
} 
var windowWidth = window.innerWidth;
window.addEventListener('resize', function() {
    
    if (window.innerWidth != windowWidth) {

        // Update the window width for next time
        windowWidth = window.innerWidth;
        setHeightToModules();
    }
});

var windowWidth2 = window.innerWidth;
window.addEventListener('resize', function() {
    
    if (window.innerWidth != windowWidth2) {

        // Update the window width for next time
        windowWidth2 = window.innerWidth;
        resizeHeadingText(false);

    }
});

// window.setTimeout(function() {
//     var event;
//     if (typeof (Event) === 'function') {
//         event = new Event('resize');
//     } else { /*IE*/
//         event = document.createEvent('Event');
//         event.initEvent('resize', true, true);
//     }
//     window.dispatchEvent(event);
// }, 300);



$(function() {
    window.setTimeout(function() {
        imagesLoaded( 'body', function( instance ) {
            resizeHeadingText(true);
        
            setHeightToModules();
            
        });
    }, 10);

    var acc = document.getElementsByClassName("accordion");

    for (var i = 0; i < acc.length; i++) {
        $(".accordion")[i].addEventListener("click", function () {
            this.classList.toggle("active");
            var panel = this.nextElementSibling;
            if (panel.style.maxHeight) {
                panel.style.maxHeight = null;
            } else {
                panel.style.maxHeight = panel.scrollHeight + "px";
            }
        });
    }
});

function UpdateQueryString(key, value, url) {
    if (!url) url = window.location.href;
    var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi"),
        hash;

    if (re.test(url)) {
        if (typeof value !== 'undefined' && value !== null) {
            return url.replace(re, '$1' + key + "=" + value + '$2$3');
        }
        else {
            hash = url.split('#');
            url = hash[0].replace(re, '$1$3').replace(/(&|\?)$/, '');
            if (typeof hash[1] !== 'undefined' && hash[1] !== null) {
                url += '#' + hash[1];
            }
            return url;
        }
    }
    else {
        if (typeof value !== 'undefined' && value !== null) {
            var separator = url.indexOf('?') !== -1 ? '&' : '?';
            hash = url.split('#');
            url = hash[0] + separator + key + '=' + value;
            if (typeof hash[1] !== 'undefined' && hash[1] !== null) {
                url += '#' + hash[1];
            }
            return url;
        }
        else {
            return url;
        }
    }
}

function getQueryParams(params, url) {

    let href = url;
    //this expression is to get the query strings
    let reg = new RegExp('[?&]' + params + '=([^&#]*)', 'i');
    let queryString = reg.exec(href);
    return queryString ? queryString[1] : null;
};


$(document).ready(function () {
    $('.tooltipster_tooltip').tooltipster({
        theme: 'tooltipster-light',
        trigger: 'click',
        interactive: true,
        contentCloning: true
    });

    // ninja fix reference numbering, for tab pages
    var inlineRefNumber = 1;
    var inlineRefs = $('.tooltipster_tooltip');
    inlineRefs.each(function () {
        if (parseInt($(this)[0].innerText, 10) < inlineRefNumber) {
            $(this)[0].innerHTML = '<sup>' + inlineRefNumber + '</sup>';
        }
        inlineRefNumber++;
    });

    if ($('.tooltip_reference').length) {
        $('#references-box').removeAttr('style');
        $('#reference-list')[0].innerHTML += "<h3 class=\"heading heading--sub\">References</h3>";
    }

    let refNumber = 0;
    $('.tooltip_reference').each(function () {
        refNumber++;
        $('#reference-list')[0].innerHTML += '<p>' + refNumber + '. ' + $(this)[0].innerHTML + '</p>';
    });

    if ($('#reference-list').is(':empty')) {
        $('.references-container-bottom').remove();
    };
});
$(document).ready(function () {
    if (/MSIE \d|Trident.*rv:/.test(navigator.userAgent) == false) {
        $.getScript("/scripts/accessibility_NonIE.js", function () {
        });
    }

    var menuItems = document.querySelectorAll('.dropdown');
    Array.prototype.forEach.call(menuItems, function (el, i) {
        //el.querySelector('a').addEventListener("click", function (event) {
        //    alert(event.code);
        //    if (this.parentNode.className == "dropdown") {
        //        this.parentNode.className = "dropdown open";
        //        this.setAttribute('aria-expanded', "true");
        //    }
           
        //    else {
        //        this.parentNode.className = "dropdown";
        //        this.setAttribute('aria-expanded', "false");
        //    }
        //    event.preventDefault();
        //    return false;
        //});
        if (el.querySelector('a')) {
            el.querySelector('a').addEventListener("keypress", function (event) {

                if (event.code == 'Space') {
                    if (this.parentNode.className == "dropdown") {
                        // close any open menu

                        for (let i = 0; i < menuItems.length; i++) {
                            let menu = menuItems[i];
                            if (menu.className == "dropdown open") {
                                menu.className = "dropdown";
                                if (menu.firstElementChild != null) menu.firstElementChild.setAttribute('aria-expanded', "false");
                            }
                        }
                        this.parentNode.className = "dropdown open";
                        this.setAttribute('aria-expanded', "true");

                    }

                    else {
                        this.parentNode.className = "dropdown";
                        this.setAttribute('aria-expanded', "false");



                    }
                    event.preventDefault();
                    return false;
                }
            });
        }       

       
    });


});

