var isMobile = false;
var gtag;
var ge = {};
var players = [];
var dataTag = [];
var dataType = [];

//Detect Mobile Browser in Javascript
//
if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent)
    || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(navigator.userAgent.substr(0, 4))) isMobile = true;

//Check for youtube embed within iframe
//
var ytemb = new RegExp('(http|https)?:\/\/(www[\.]|)?[\.]?youtube[\.]?com\/embed\/.*$');

//Email Regex
var er = new RegExp('^((?:(?:(?:[a-zA-Z0-9][\\.\\-\\+_]?)*)[a-zA-Z0-9])+)\\@((?:(?:(?:[a-zA-Z0-9][\\.\\-_]?){0,62})[a-zA-Z0-9])+)\\.([a-zA-Z0-9]{2,})$');

//Add more event track actions here so that they become consistant for each event we track.
//Call within the track event function as 'ge.click' which will populate the event action with the value from this array
//
ge.click = "click";
ge.videoplay = "video-play";
ge.videopause = "video-paused";
ge.videoend = "video-end";

$(document).ready(function () {
    
    
    // **********************************
    // Force http links to blank window
    //
    $("a[href]").each(function() {
        var t = $(this);
        var h = t.attr("href").toLowerCase();
        if (h) {
            if (h.length > 4) {
                if (h.substring(0,4)=="http") {
                  t.attr("target","_blank");
                }
            }
        }
    });
    // **********************************
	
	$('.hero-carousel').slick({
        dots: false,
        infinite: true,
        speed: 300,
        slidesToShow: 1,
        autoplay: true,
        autoplayspeed: 5000
	});
			
	$('.related-carousel').slick({
		dots: true,
		infinite: true,
		appendArrows: ('.carousel-nav'),
		appendDots: ('.carousel-nav'),
		speed: 300,
        slidesToShow: 4,
        slidesToScroll: 4,
		responsive: [
		{
		  breakpoint: 1024,
		  settings: {
			slidesToShow: 3,
			slidesToScroll: 3,
			infinite: true,
			dots: true
		  }
		},
		{
		  breakpoint: 767,
		  settings: {
			slidesToShow: 2,
			slidesToScroll: 2
		  }
		},
		{
		  breakpoint: 500,
		  settings: {
			slidesToShow: 1,
			slidesToScroll: 1
		  }
		}
	  ]	});
	
    $(".panel-person").click(function (e) {
        if ($(".panel-person").hasClass("active") && !$(this).hasClass("active")) {
            $(".panel-person").removeClass("active");
        }

		$(this).toggleClass("active");
		e.preventDefault();
	});
	
	
	
   $('.hero-panel-text').matchHeight({
	   byRow: false,
	   mobile: false
   });	
	
	
   if (typeof Sys !== "undefined") {
      // Event handler for ASPs Page Request Manager.
      // We are looking to see when an UpdatePanel has been updated.
      //
      Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(SF_beginRequest);
      Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(SF_pageLoaded);
      Sys.WebForms.PageRequestManager.getInstance().add_endRequest(SF_endRequest);
   }

	$('.nav-icon').click(function () {
        $(this).toggleClass('open');
        $("nav").toggleClass('open');
        $(".logo-container").toggleClass('open');
    });

    

    //GA Event Tracking for every 'a' and 'area' click.
    $(document).on("click", "a,area", function (e) {

        try {

            var t = $(this);
            var tHref = t.attr("href");
            var tTarget = t.attr("target");
            var linkType = "Internal";
            var tagName = $(this).prop("tagName").toLowerCase();
            var trackLink = true;
            var eventLabel = "";

            //Check we have a link to track
            //
            if (tHref != null && typeof tHref != "undefined" && tHref.length > 0) {

                tHref = tHref.toLowerCase();
                eventLabel = t.attr("href");

                //Check which type of link this is (mailto,http etc)
                //
                if (tHref == "#") {
                    if (tagName == "area") {
                        if (t.attr("alt") != null && typeof t.attr("alt") != "undefined" && t.attr("alt").length > 0) {
                            eventLabel = t.attr("alt");
                            linkType = "Image Map"
                        } else {
                            trackLink = false;
                        }
                    } else {
                        trackLink = false;
                    }
                } else if ((tHref.length > 1) && (tHref.indexOf("#") > -1) && (tHref.indexOf("http") == -1)) {
                    linkType = "Anchor";
                } else if ((tHref.length > 1) && (tHref.toLowerCase().indexOf("mailto:") > -1)) {
                    linkType = "Mail";
                } else {
                    if (tHref.indexOf("http://") > -1 || tHref.indexOf("https://") > -1) {
                        if (tTarget != null && typeof tTarget != "undefined") {
                            if (tTarget == "_blank") {
                                linkType = "External New Window";
                            } else {
                                linkType = "External Same Window";
                            }
                        }
                        else {
                            linkType = "External Same Window";
                        }
                    }
                }

                if (trackLink) {
                    AM_TrackEvent(ge.click, "Link (" + linkType + ")", eventLabel);
                }

            }

        } catch (message) {

        }

    });
    //


    //Cookie Policy
    $(".cookieBar .acceptBtn").click(function (e) {
        $(this).parent().slideUp();
        e.preventDefault();
    });
    //

    //Social Sharing
    $(".share-toggle").click(function (e) {
        $(".share-lightbox").fadeToggle();
        e.preventDefault();
    });

    $(".share-fade").click(function () {
        $(".share-lightbox").fadeToggle();
    });
    //


    //Play HTML5 Video
    $(".play-page-video").click(function (e) {

        var t = $(this);
        var tID = t.attr("data-id");
        var video;

        if (tID != null && typeof tID != "undefined") {
            t.hide();
            video = document.getElementById(tID);
            AM_PlayVideo(video);
        }

        e.preventDefault();
    });
    //

    //Check for Youtube Video Embed Iframe on this page
    //
    if (AM_YoutubeEmbed()) {

        try {
            var tag = document.createElement('script');
            tag.id = 'ytapi';
            tag.src = 'https://www.youtube.com/iframe_api';
            var firstScriptTag = document.getElementsByTagName('script')[0];
            firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

            //Go to: onYouTubeIframeAPIReady()

        } catch (message) {

        }
    }

});

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

    var url = window.location.href.toLowerCase();
    if (url.includes('#')) {
        url = url.split('#')[1];

        url = "." + url;

        var match = false;
        var makeInactive = [];

        $(".insightTagsBtn").each(function () {
            var value = $(this).data("id");

            if (value !== "*") {
                if (value === url) {
                    match = true;
                }
                else {
                    makeInactive.push($(this).data("id"));
                }
            }
        });

        if (match) {
            $(".insightTagsBtn").each(function () {
                var dataID = $(this).data("id");
                if (makeInactive.includes(dataID) && dataID !== "*") {
                    $(this).addClass("inactive");
                }
            });

            console.log(makeInactive);
            dataTag = [];
            dataTag.push(url);
            genFilter();
        }
        else
        {
            window.location.replace(window.location.href.toLowerCase().split('#')[0]);
        }

    }
	
	
	$(".insightTagsBtn2").click(function (e) {

		//var did = $(this).data("id");
		//filterInsights(did)
		
    });
	
	

    $(".insightTagsBtn").click(function (e) {
	

        var value = $(this).data("id");
        console.log(value);
        filterInsights(value);



        e.preventDefault();
    });

    $(".insightTypeBtn").click(function(e){
        var value = $(this).data("id");
        var count = 0;

        $(".insightTypeBtn").each(function () {
            count++;
        });

        if (value !== "*") {
            if (!dataType.includes(value)) {
                dataType.push(value);
            }
            else {
                dataType = arrayRemove(dataType, value);
            }
        }
        else {
            dataTag = [];
            dataType = [];
        }

        $(".insightTagsBtn").each(function () {

            $(this).removeClass("inactive");
            if (dataTag.length === count - 1) {
                dataTag = [];
            }
            else if (dataTag.length > 0) {
                var dataID = $(this).data("id");

                if (!dataTag.includes(dataID) && dataID !== "*") {
                    $(this).addClass("inactive");
                }
            }
        });

        $(".insightTypeBtn").each(function () {
            $(this).removeClass("inactive");
            if (dataType.length === count) {
                dataType = [];
            }
            else if (dataType.length > 0) {
                var dataID = $(this).data("id");

                if (!dataType.includes(dataID) && dataID !== "*") {
                    $(this).addClass("inactive");
                }
            }
        }); 

        genFilter();
    });
});



function genFilter() {
    var $iso = $('.panel-listing-section .col-row').isotope({
        itemSelector: '.panel-listing-section .col-4'
    });

    var output = "";

    if (dataTag.length > 0 && dataType.length > 0)
    {
        for (var x = 0; x < dataTag.length; x++) {
            for (var y = 0; y < dataType.length; y++) {
                if (x === 0 && y === 0) {
                    output += dataTag[x] + "" + dataType[y];
                }
                else
                {
                    output += ","  + dataTag[x] + "" + dataType[y];
                }
            }
        }
    }
    else
    {
        if (dataTag.length > 0)
        {
            for (var i = 0; i < dataTag.length; i++) {
                if (i > 0) { output += ", " + dataTag[i]; }
                else { output = dataTag[i]; }
            }
        }
        else if (dataType.length > 0)
        {
            for (var j = 0; j < dataType.length; j++) {
                if (j > 0) { output += ", " + dataType[j]; }
                else { output = dataType[j]; }
            }
        }
    }

    $iso.isotope({
        filter: output
    });
}

function arrayRemove(arr, value) {

    return arr.filter(function (ele) {
        return ele !== value;
    });

}

function AM_TrackEvent(eventAction, eventCategory, eventLabel, eventValue) {
    var tagarray = [];
    //Function that tracks an event click and sends to Google (if a GA Code is present)
    //
    //<action>*     = the string that will appear as the event action in Google Analytics Event reports.
    //<category>    = the string that will appear as the event category.
    //<label>       = the string that will appear as the event label.
    //<value>       = a non-negative integer that will appear as the event value.
    //* = Required attribute.

    //Example template of gtag event tracking:
    //gtag('event', <action>, {'event_category': <category>, 'event_label': <label>, 'value':<value>});

    //Example Events below:
    //gtag('event', 'download', {'event_category': 'PDF', 'event_label': '/salesForms/orderForm1.pdf', 'value':<value>});

    if (gtag) {

        var data = {};
        if (eventCategory) { data.event_category = eventCategory; }
        if (eventLabel) { data.event_label = eventLabel; }
        if (eventValue) { data.value = eventValue; }
        tagarray.push(data);
        gtag('event', eventAction, data);

    }

    //More info:    
    //https://developers.google.com/analytics/devguides/collection/gtagjs/events
    //https://support.google.com/analytics/answer/1033068#Anatomy

}

function AM_PlayVideo(video) {

    //Function that plays a HTML5 video when the play button is clicked
    //
    //Add the controls to the video and start playing.
    video.setAttribute("controls", "controls");
    video.play();
}

function AM_RestartVideo(video) {

    //Function that restarts the video once it has finished playing.
    //
    //Once the video as finished reload it so it can be played again.
    var restartVideo = document.getElementById(video);
    restartVideo.removeAttribute("controls");
    restartVideo.load();
    $(".play-page-video[data-id=" + video + "]").show();
}

function AM_RestartAllVideos() {

    //Function that loops through each video on the page that is NOT a background video, and stops them playing and reloads ready to play again.
    //
    $("video.video-html5").each(function () {
        $(this)[0].load();
        $(this)[0].removeAttribute("controls");
        $(this).prev(".play-page-video").show();
    });

}

function AM_YoutubeEmbed() {
    //Function that checks to see if a youtube embed iframe exists on this page.
    //If it does, we can set up video event tracking (if GA Code present)
    //
    var exists = false;
    if (gtag) {
        for (var e = document.getElementsByTagName("iframe"), x = 0; x < e.length; x++) {

            if (ytemb.test(e[x].src)) {
                //If this tag has no id then we can add one
                if (e[x].id == null || typeof e[x].id == "undefined" || e[x].id.length < 1) {
                    e[x].setAttribute("id", "ytemb" + x);
                }

                var src = e[x].src;
                if (src.indexOf("enablejsapi") === -1) {
                    //append to end of querystring
                    //
                    if (src.indexOf("?") > -1) {
                        src = src + "&enablejsapi=1";
                    } else {
                        src = src + "?enablejsapi=1";
                    }

                    e[x].setAttribute("src", src);

                }

                exists = true;
            }
        }
    }
    return exists;
}

function onPlayerStateChange(event) {
    try {
		
		var player = players[event.target.a.id][0];
		var videoData = player.getVideoData();
		var eventLabel = videoData.title;
		
        if (eventLabel != null && typeof eventLabel != "undefined") {
            var videoAction = "";

            //Fire GA Event to track what the user is doing with the video
            if (event.data == YT.PlayerState.ENDED) {
                videoAction = ge.videoend;
            } else if (event.data == YT.PlayerState.PAUSED) {
                videoAction = ge.videopause;
            } else if (event.data == YT.PlayerState.PLAYING) {
                videoAction = ge.videoplay;
            }

            AM_TrackEvent(videoAction, "Video (YouTube)", eventLabel);
        }
    } catch (message) {

    }
}

function onYouTubeIframeAPIReady() {
    for (var e = document.getElementsByTagName("iframe"), x = 0; x < e.length; x++) {
        if (ytemb.test(e[x].src)) {
            var player = new YT.Player(e[x].id, { events: { 'onStateChange': onPlayerStateChange } });
            players.push(player);
        }
    }
}

function IsNull(obj) {
    if ((obj != null) && (typeof obj != "undefined") && (obj.length) > 0) {
        return false;
    } else {
        return true;
    }
}

// Raised before processing of an asynchronous postback starts and the postback is sent to the server.
// You can use this event to set request headers or to begin an animation that indicates that the page
// is processing.
//
function SF_beginRequest(sender, args) {
   // Need to delete any datepickers so it will remove the HTML that it adds for the popup picker.
   //
   unbindDatePickers();
}

// Raised after all content on the page is refreshed, as a result of either a synchronous or an
// asynchronous postback. You can use this event to provide a custom transition effect for updated
// content.
//
function SF_pageLoaded(sender, args) {
   // Page this file is included in can have a "pageLoaded" function defined.
   //
   if (typeof pageLoaded == "function") {
      pageLoaded(sender, args);
   }
}

// Raised after an asynchronous postback is finished and control has been returned to the browser.
// You can use this event to provide a notification to users or to log errors.
//
function SF_endRequest(sender, args) {
   rebindDatePickers();
   //rebindTrackChanges();

   // Page this file is included in can have a "pageReloaded" function defined.
   //
   if (typeof endRequest == "function") {
      endRequest(sender, args);
   }
}

// Set up any date and date/time pickers.
//
function rebindDatePickers() {
   if (typeof $.fn.datetimepicker != "undefined") {
      $(".datetimepicker")
         .datetimepicker("destroy")
         .datetimepicker({
            format: "d/m/Y H:i:s",
            allowBlank: true/*,
            onChangeDateTime: function (e, f) {
               if (f.hasClass("track-change")) {
                  markFormChanged();
               }
            }*/
         });

      $(".datepicker")
         .datetimepicker("destroy")
         .datetimepicker({
            format: "d/m/Y",
            allowBlank: true,
            timepicker: false/*,
            onChangeDateTime: function (e, f) {
               if (f.hasClass("track-change")) {
                  markFormChanged();
               }
            }*/
         });
   }
}

// Undind datetimepickers.
// Need to do this otherwise it leaves the picker HTML code within the document.
//
function unbindDatePickers() {
   if (typeof $.fn.datetimepicker != "undefined") {
      $(".datetimepicker,.datepicker").datetimepicker("destroy");
   }
}

// Encode text that may contain HTML; < becomes &lt;    & becomes &amp;   etc.
//
function htmlEncode(html) {
   return document.createElement('a').appendChild(document.createTextNode(html)).parentNode.innerHTML;
};

// Decode text that is HTML encoded.
//
function htmlDecode(html) {
   var a = document.createElement('a'); a.innerHTML = html;
   return a.textContent;
};

// Get the selection start position within an <input> or <textarea>
//
function getSelectionStart(inputField) {
   if (inputField.createTextRange) {
      var r = document.selection.createRange().duplicate();
      r.moveEnd('character', inputField.value.length);

      if (r.text == '') return inputField.value.length;

      return inputField.value.lastIndexOf(r.text);
   }
   else
      return inputField.selectionStart;
}

// Get the selection end position within an <input> or <textarea>
//
function getSelectionEnd(inputField) {
   if (inputField.createTextRange) {
      var r = document.selection.createRange().duplicate();

      r.moveStart('character', -inputField.value.length);

      return r.text.length;
   }
   else
      return inputField.selectionEnd;
}

// Set the caret position within an <input> or <textarea>
//
function setCaretPosition(inputField, position) {
   if (inputField != null) {
      if (inputField.createTextRange) {
         var range = inputField.createTextRange();
         range.move('character', position);
         range.select();
      }
      else if (inputField.selectionStart) {
         inputField.focus();
         inputField.setSelectionRange(position, position);
      }
      else
         inputField.focus();
   }
}

// Object to show a slide-out message to indicate an action has been performed.
// It requires a div which contains a span. The message will be placed in to the span, and then the div will be slid down.
// Depending on which function is called, it will also add the class "success" or "failed" to the div.
//
// actionStatus.success("Update successful");
// actionStatus.failed("Update failed");
//
var actionStatus = (function () {
   function ActionStatus() {
      var timer = null;
      var panel = null;
      var panelText = null;

      this.success = function (msg) {
         showMessage(true, msg);
      }

      this.failed = function (msg) {
         showMessage(false, msg);
      }

      var showMessage = function (success, msg) {
         if (panel == null) {
            // This will need to be created - probably in the master page, below the header.
            //
            panel = $("header").find(".action-status");
            panelText = panel.find("span");
         }

         if (timer != null) {
            clearTimeout(timer);
            timer = null;
         }

         panelText.text(msg);

         panel
            .removeClass("success failed")
            .addClass(success ? "success" : "failed")
            .slideDown(200);

         timer = setTimeout(function () { timer = null; panel.slideUp(200); }, 3000);
      };

      this.close = function () {
         if (timer != null) {
            clearTimeout(timer);
            timer = null;
         }

         panel.slideUp(200);

         return false;
      }
   }

   return new ActionStatus();
})();

// Object to show/hide a spinner when doing busy work.
//
var spinner = (function () {
   function Spinner() {
      var shown = false;
      var div = null;

      this.show = function () {
         if (!shown) {
            // CSS is used to position and spin this div.
            //
            div = $("<div class=\"lds-ring\"><div></div><div></div><div></div><div></div></div>").appendTo("body");
            shown = true;
         }
      }

      this.hide = function () {
         if (shown) {
            if (div != null) {
               div.remove();
               div = null;
            }
            shown = false;
         }
      }
   }

   return new Spinner();
})();


/********** Tiny MCE **********/

// Turn selected elements in to tinyMCE editors with a standard set of features.
//
function fullTinyMCE(selector) {
   tinymce.init({
      selector: selector,           //".tinymce",
      encoding: "xml",              // Tell tinyMCE to return XML encoded content.
      plugins: ["link", "hr"],
      menu: {
         insert: { title: "Insert", items: "link | hr" },
         edit: { title: "Edit", items: "undo redo | cut copy paste | selectall" },
         format: { title: "Format", items: "bold italic underline strikethrough superscript subscript | formats | removeformat" },
      },
      toolbar1: "undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist | outdent indent"
   });
}

// Turn selected elements in to tinyMCE editors with a limited set of features.
//
function miniTinyMCE(selector) {
   // Simpler tinymce, with only a simple toolbar and no status bar.
   //
   tinymce.init({
      selector: selector,           //".tinymce-min",
      encoding: "xml",              // Tell tinyMCE to return XML encoded content.
      plugins: ["link", "hr"],
      menu: {},
      toolbar1: "undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist link | outdent indent",
      statusbar: false
   });
}

// Forces all tinyMCE controls to update their original controls with the content.
//
function saveTinyMCEs() {
   tinyMCE.triggerSave();
}



function filterInsights(v) {


   var value = v;
   var count = 0;

   $(".insightTagsBtn").each(function () {
      count++;
   });

   if (value !== "*") {
      if (!dataTag.includes(value)) {
         dataTag.push(value);
      }
      else {
         dataTag = arrayRemove(dataTag, value);
      }
   }
   else {
      dataTag = [];
      dataType = [];
   }

   $(".insightTagsBtn").each(function () {

      $(this).removeClass("inactive");
      if (dataTag.length === count - 1) {
         dataTag = [];
      }
      else if (dataTag.length > 0) {
         var dataID = $(this).data("id");

         if (!dataTag.includes(dataID) && dataID !== "*") {
            $(this).addClass("inactive");
         }
      }
   });

   $(".insightTypeBtn").each(function () {
      $(this).removeClass("inactive");
      if (dataType.length === count) {
         dataType = [];
      }
      else if (dataType.length > 0) {
         var dataID = $(this).data("id");

         if (!dataType.includes(dataID) && dataID !== "*") {
            $(this).addClass("inactive");
         }
      }
   });

   genFilter();
}

// Calculate an elements position in relation to the current view port.
// Determines if the element is above or below, and how far.
//
function CalculateElementPositionInViewport(element, threshold) {
   threshold = threshold || 0;

   element = $(element);

   if (element.length > 0) {
      var elementPosition = element.offset();
      var elementHeight = element.height();
      var viewHeight = $(window).height();
      var scrollTop = $(window).scrollTop();

      var elementOffset = elementPosition.top - scrollTop;

      var above = (elementOffset + elementHeight - threshold) < 0;
      var below = (elementOffset + threshold) >= viewHeight;

      var distance = 0;

      if (above) {
         distance = -elementOffset + threshold;
      }
      else if (below) {
         distance = elementOffset - viewHeight + elementHeight + threshold;
      }

      var result = {
         scrollTop: scrollTop,
         elementTop: elementPosition.top,
         elementHeight: elementHeight,
         viewHeight: viewHeight,
         above: above,
         below: below,
         distance: distance
      };
   }
   else {
      result = null;
   }

   return result;
}

// Scroll the window so that the specified element is at or near the top of the window.
//
function ScrollElementToTop(element, threshold, speed) {
   threshold = threshold || 0;
   speed = speed || 800;

   element = $(element);

   var result = CalculateElementPositionInViewport(element, threshold);

   if (result != null) {
      $("html,body").animate({ "scrollTop": result.elementTop - threshold }, speed);
   }
}

// Scroll the window so that the specified element is at or near the bottom of the window.
//
function ScrollElementToBottom(element, threshold, speed) {
   threshold = threshold || 0;
   speed = speed || 800;

   element = $(element);

   var result = CalculateElementPositionInViewport(element, threshold);

   if (result != null) {
      $("html,body").animate({ "scrollTop": result.elementTop - result.viewHeight + threshold }, speed);
   }
}









