/********* Dynamically setting iframe height - Justin ****/
//commenting out because registration is breaking
/*function iframeLoaded() {
    var iFrameID = document.getElementById('bcbst-frame');
    if (iFrameID) {
        // here you can make the height, I delete it first, then I make it again
        var myContHeight = iFrameID.contentWindow.document.body.scrollHeight+150;
        iFrameID.style.minHeight = "";
        iFrameID.style.minHeight = myContHeight + "px";
        console.log("iFrame Content: " + myContHeight + "px");
    }
}
*/
/********* Scrolling sneak peek added by Chetan ****/

try {
    //var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ? true : false;
    $(document).ready(function () {
        //if (isMobile) 

        //if (window.outerWidth <= 767) {
if (window.matchMedia("(max-width: 421px)").matches) {
$(".carousel .item").each(function () {
                var next = $(this).next();
        if (!next.length) {
            next = $(this).siblings(':first');
        }
        next.children(':first-child').clone().appendTo($(this));
        if (next.next().length > 0) {
            next.next().children(':first-child').clone().appendTo($(this));
        } else {
            $(this).siblings(':first').children(':first-child').clone().appendTo($(this));
        }
            })
            
        }


    });

} catch (error) {
    console.log("swipe sneak peek error: " + error)
}
/******* End here*******/



/*  --------------- Login box SCROLLING functionality --------------- */
$(document).ready(function () {
    if (location.href.indexOf("bcbst.com/index") > -1) {
        var myLogin = document.getElementById("login-form");
        var myLoginHeight = myLogin.scrollHeight;
        var loginDropdown = document.getElementsByClassName("login-dropdown");
        var headerRight = document.getElementsByClassName("header-right-container");
        var heroForm = document.getElementsByClassName("hero-form");

        function loginDropHide() {
            try {
                if (!($(this).scrollTop() >= (($(myLogin).position().top) + myLoginHeight))) {
                    loginDropdown[0].style.display = "none";
                    headerRight[0].style.paddingRight = "100px";
                }
                $(document).on('scroll', function () {
                    if (window.outerWidth < 992 || $(this).scrollTop() >= (($(myLogin).position().top) + myLoginHeight)) {
                        loginDropdown[0].style.display = "flex";
                        headerRight[0].style.paddingRight = "0px";
                    } else {
                        loginDropdown[0].style.display = "none";
                        headerRight[0].style.paddingRight = "100px";
                        document.getElementsByClassName("header-right-container")[0].classList.remove("open");
                    }
                }); //-->
            } catch (error) {
                console.log("login scroll function error: " + error)
            }
        }
        window.onresize = function () {
            if (window.outerWidth >= 992) {
                loginDropHide();
            } else {
                loginDropdown[0].style.display = "flex";
                headerRight[0].style.paddingRight = "0px";
            }
        }
        loginDropHide();
    }


});


/*  --------------- Login box LOGIN functionality --------------- */
var brokerLoginURL;
var employerLoginURL;
var memberLoginURL;
if(window.location.host=="www.bcbst.com"||window.location.host=="bcbst.com"){
    brokerLoginURL = "https://sso.bcbst.com/pf/adapter2adapter.ping?IdpAdapterId=FormIDPAdapterBrokerPortal&SpSessionAuthnAdapterId=FormLoginBroker";
    employerLoginURL ="https://sso.bcbst.com/pf/adapter2adapter.ping?IdpAdapterId=FormIDPAdapterEmployerPortal&SpSessionAuthnAdapterId=FormLoginEmployer";
    memberLoginURL ="https://sso.bcbst.com/pf/adapter2adapter.ping?IdpAdapterId=FormIDPAdapterMemberPortal&SpSessionAuthnAdapterId=LoginTest";
} else if(window.location.host=="test.bcbst.com"){
    brokerLoginURL = "https://sso2.bcbst.com/pf/adapter2adapter.ping?IdpAdapterId=FormIDPAdapterBrokerPortal&SpSessionAuthnAdapterId=LoginTestBroker";
    employerLoginURL ="https://sso2.bcbst.com/pf/adapter2adapter.ping?IdpAdapterId=FormIDPAdapterEmployerPortal&SpSessionAuthnAdapterId=LoginTestEmployer";
    memberLoginURL ="https://sso2.bcbst.com/pf/adapter2adapter.ping?IdpAdapterId=FormIDPAdapterMemberPortal&SpSessionAuthnAdapterId=LoginTest";
} else if(window.location.host=="public-dev.bcbst.com"){
    brokerLoginURL = "https://sso2.bcbst.com/pf/adapter2adapter.ping?IdpAdapterId=FormIDPAdapterBrokerPortal&SpSessionAuthnAdapterId=LoginTestBroker";
    employerLoginURL ="https://sso2.bcbst.com/pf/adapter2adapter.ping?IdpAdapterId=FormIDPAdapterEmployerPortal&SpSessionAuthnAdapterId=LoginTestEmployer";
    memberLoginURL ="https://sso2.bcbst.com/pf/adapter2adapter.ping?IdpAdapterId=FormIDPAdapterMemberPortal&SpSessionAuthnAdapterId=LoginTest";
}


/******** Form Submission for Hero Logins ***********/
function postOk() {
    try {
        if (location.href.indexOf("bcbst.com/get-care/personalized-care/managing-chronic-conditions/diabetes") > -1||
           location.href.indexOf("/get-care/personalized-care/managing-chronic-conditions/heart-conditions") > -1||
           location.href.indexOf("/get-care/personalized-care/managing-chronic-conditions/respiratory-health") > -1||
           location.href.indexOf("/get-care/personalized-care/managing-chronic-conditions/behavioral-health") > -1) {
            window.location.href="https://members.bcbst.com/wps/myportal/member/home/managingyourhealth/caremanagement";
            return false;
        }
        var ok = document.getElementById('ok');
        ok.value = 'clicked';
        var myUser = document.getElementById('username').value;
        var myDropdown = document.getElementById('accountType');

        //If it isn't "undefined" and it isn't "null", then it exists.
        if (typeof (mydropdown) != 'undefined' && myDropdown != null) {
            cmCreateRegistrationTag(myUser, "", "", "", "", "", myDropdown.options[myDropdown.selectedIndex].text + "-_-" + window.location.href.split('!')[0]);
        } else {
            cmCreateRegistrationTag(myUser, "", "", "", "", "", "Member-_-" + window.location.href.split('!')[0]);
        }
        document.getElementById('login-form').submit();
        return false;
    } catch (error) {
        console.log("error " + error);
    }
}

/******** Form Submission for Header Logins ***********/
function postOkheader() {
    try {
        var ok = document.getElementById('okheader');
        ok.value = 'clicked';
        var myUser = document.getElementById('usernameh').value;
        var myDropdown = document.getElementById('accountTypeh');
        cmCreateRegistrationTag(myUser, "", "", "", "", "", myDropdown.options[myDropdown.selectedIndex].text + '-_-' + window.location.href.split('!')[0]);
        document.getElementById('login-form-header').submit();
        return false;
    } catch (error) {
        console.log("error " + error);
    }
}

function updateURL(loginSelection) {
    if (loginSelection == "mem") {
        document.getElementById("login-form-header").action = memberLoginURL;
        document.getElementById("registration-link").setAttribute("href", "/register/?reg=MEMV");
    } else if (loginSelection == "bro") {
        document.getElementById("login-form-header").action = brokerLoginURL;
        document.getElementById("registration-link").setAttribute("href", "/register/?reg=broker");
    } else if (loginSelection == "emp") {
        document.getElementById("login-form-header").action = employerLoginURL;
        document.getElementById("registration-link").setAttribute("href", "/register/?reg=EMPV");
    } else if (loginSelection == "pro") {
        window.location.href = "/providers/index.page";
    }
}

function updateURL2(loginSelection) {
    if (loginSelection == "mem") {
        document.getElementById("login-form").action = memberLoginURL;
        document.getElementById("hero-registration-link").setAttribute("href", "/register/?reg=MEMV");
    } else if (loginSelection == "bro") {
        document.getElementById("login-form").action = brokerLoginURL;
        document.getElementById("hero-registration-link").setAttribute("href", "/register/?reg=broker");
    } else if (loginSelection == "emp") {
        document.getElementById("login-form").action = employerLoginURL;
        document.getElementById("hero-registration-link").setAttribute("href", "/register/?reg=EMPV");
    } else if (loginSelection == "pro") {
        window.location.href = "/providers/index.page";
    }
}
/*  --------------- HTML5 Speech Recognition API --------------- */
/*  ---------------     Future Implementation    ----------------*/
/*function startDictation() {
        if (window.hasOwnProperty('webkitSpeechRecognition')) {
            var recognition = new webkitSpeechRecognition();
            recognition.continuous = false;
            recognition.interimResults = false;
            recognition.lang = "en-US";
            recognition.start();
            console.log(recognition);
            console.log("speech recognition initiated");
            recognition.onspeechend=function(){
                console.log("speech has stopped being detected");
            }
            
            recognition.onresult = function(e) {
                console.log("speech results received");
                document.getElementById('search-input').value = e.results[0][0].transcript;
                console.log(e.results[0][0].transcript);
                recognition.stop();
                document.getElementById('siteSearch').submit();
            };
            recognition.onerror = function(e) {
                console.log("speech recognition error");
                console.log(e);
                recognition.stop();
            }
        }
    }

*/


/*  --------------- Accordion JS --------------- */
/*$(function () {
  var $card = $('.component-text-accordion-card');

  $card.on('click', function () {
      var $this = $(this);
      var className = 'open';

      $this.toggleClass(className)
  });
});*/

$(function () {
    var $back = $('.component-text-accordion-content-back-link');
    //var $card = $('.component-text-accordion-card');
    var $card = $('li.component-text-accordion-card'); //only highest level cards

    $back.on('click', function (e) {
        e.preventDefault();

        var $ul = $card.closest('.component-text-accordion-items');
        var $subMenu = $(this).closest('.component-text-accordion-submenu');

        $subMenu.removeClass('show');
        $ul.addClass('show');
    });

    $card.on('click', function () {
        var $this = $(this);
        var defaultClassName = 'default';
        var className = 'open';

        var $accordion = $this.closest('.component-text-accordion.forms');
        var $ul = $this.closest('.component-text-accordion-items');

        if ($ul.length) {
            //var $cards = $ul.find('.component-text-accordion-card');
            var $cards = $ul.find('li.component-text-accordion-card'); //only highest level cards
            var index = $cards.index(this);
            var $subMenus = $ul.siblings('.component-text-accordion-submenu');
            var $subMenu = $subMenus.eq(index);

            if ($subMenu.length) {
                $accordion.find('.' + defaultClassName).removeClass(defaultClassName);

                $ul.removeClass('show');
                $cards.removeClass(className);
                $subMenus.removeClass('show');
                $subMenu.addClass('show');
                $subMenu.addClass('default');
            }
        }

        $this.toggleClass(className)
    });

    //BEGIN toggle of lowest-level accordion cards
    $('.component-text-accordion-card-header').on('click', function () {
        var $this = $(this);
        var className = 'open';
        var elementStatus = "noOpen";
        if ($this.closest(".component-text-accordion-card").hasClass(className)) {
            elementStatus = "yesOpen";
        }
        $("div.component-text-accordion-card").removeClass('open'); //only lowest level cards
        if (elementStatus == "noOpen") {
            $this.closest(".component-text-accordion-card").addClass(className);
        }
    });
});

/*  --------------- Dropdown JS --------------- */
/*$("#inlineFormCustomSelectPref-upper").change(dropdownSelection);

function dropdownSelection() {
	var selection = $("#inlineFormCustomSelectPref-upper").val();
	if (selection == 0) {
		$(".sec__imageText.homepage .option-one").css("display", "block");
		$(".sec__imageText.homepage .option-two").css("display", "none");
	} else if (selection == 1) {
		$(".sec__imageText.homepage .option-one").css("display", "none");
		$(".sec__imageText.homepage .option-two").css("display", "block");
	} else {
		$(".sec__imageText.homepage .option-one").css("display", "none");
		$(".sec__imageText.homepage .option-two").css("display", "none");
	}
}*/
$(function () {
    var $dropdownButtonText = $('#component-dropdown-button-text');
    var $menuItems = $('.component-dropdown-menu-item');

    $menuItems.each(function () {
        var $this = $(this);

        $this.on('click', function () {
            $dropdownButtonText.text($this.text());
        });
    });
});


/* --------------------- Plan Cards ---------------------*/
$(function () {
    var $planCards = $('.plan-card');

    $planCards.on('click', function () {
        var $this = $(this);
        var $cardsWrapper = $this.parents('#plan-cards');
        var expandedClass = 'plan-card-expanded';

        $cardsWrapper.find('.' + expandedClass).removeClass(expandedClass);

        $cardsWrapper.addClass('expanded');
        $this.addClass(expandedClass);

        $this.children('.plan-card-close').on('click', function (event) {
            event.stopPropagation();

            $cardsWrapper.removeClass('expanded');
            $this.removeClass(expandedClass);

            $(this).off('click');
        });
    });
});
/*  --------------- Global Navigation Header Login JS --------------- */
$(function () {
    const $loginButton = $('.lay__header .login-dropdown, .lay__header .login-form-close');
    const $loginForm = $('.lay__header .header-right-container');

    $loginButton.on('click', function loginButtonClickHandler(e) {
        const className = 'open';

        if ($loginForm.hasClass(className)) {
            $loginForm.removeClass(className);

            return;
        }

        $loginForm.addClass(className);
    });
});

/*  --------------- Hero Homepage JS --------------- */
$(function () {
    const $heroIcons = $('.hero-icons');
    const $heroSlide = $('.hero-slide');

    $heroIcons.on('click', '.hero-icon', function heroIconClickHandler(e) {
        const $this = $(this);
        const className = 'clicked';

        if (!$this.hasClass(className)) {
            const $heroIcon = $('.hero-icon', $heroIcons);

            $heroIcon.removeClass(className);
            $heroSlide.addClass('hide')

            $this.addClass(className);

            const selectedIndex = $heroIcon.index(this) + 1;

            $heroSlide.eq(selectedIndex).removeClass('hide');
        }
    });
});

/*  --------------- Menu JS --------------- */
$(document).ready(function () {
    let cache = {
        closeBtn: $("#close-search"),
        closeBtnDk: $("#close-search-dk"),
        search: $("#do-search"),
        searchDk: $("#do-search-dk"),
        mobileNav: $("#mobile-nav"),
        desktopNav: $("#desktop-nav")
    };

    const mqMobile = window.matchMedia('(max-width: 767px)');

    const adjustMenu = function () {
        cache.closeBtn.on('click touchstart', function (e) {
            e.preventDefault();
            cache.mobileNav.find('.search-container').fadeOut('fast').removeClass('show');
        });

        cache.search.on('click touchstart', function (e) {
            e.preventDefault();
            cache.mobileNav.find('.search-container').addClass('show').fadeIn('fast');
        });
    };

    mqMobile.addListener = function () {
        if (mqMobile.matches) {
            adjustMenu();
        }
    };

    adjustMenu();
    //  listeners desktop
    cache.searchDk.on('click', function (e) {
        e.preventDefault();
        cache.desktopNav.find('.search-container').addClass('show').fadeIn('fast');
        $(this).hide();
    });

    cache.closeBtnDk.on('click', function (e) {
        e.preventDefault();
        cache.desktopNav.find('.search-container').fadeOut('fast').removeClass('show');
        cache.searchDk.show();
    });


});

/*  --------------- scrollspy JS --------------- */
/*!
 * BCBST timeline Plugin
 * Author: Hangar Interactive
 * version: 1.0
 * Licensed under the MIT license
 */
;
(function ($, window, document, undefined) {
    $.fn.extend({
        BCBSTScrollSpy: function (options) {
            let defaults = {
                jumpToClass: '.jump-to',
                animate: false,
                containers: {}
            };

            // Add any overriden options to a new object
            options = $.extend({}, defaults, options);

            var setNavHeight = function (_navigation) {
                return _navigation.getBoundingClientRect().height;
            };

            var animateOnScroll = function (_links, _nav) {
                let distance = 0,
                    localNavHeight = setNavHeight(_nav);

                _links.on('click', function (e) {
                    e.preventDefault();

                    const body = $('html, body'),
                        id = $(this).attr('href'),
                        queryId = id.substring(1, id.length);

                    if ($(id).length) {
                        distance = ($(_nav).length) ? (document.querySelector('[id="${queryId}"]').getBoundingClientRect().top - localNavHeight) : document.querySelector('[id="${queryId}"]').getBoundingClientRect().top;

                        body.animate({
                            scrollTop: distance + window.pageYOffset
                        }, 1000);
                    }
                });
            }

            return this.each(function () {
                const navId = $(this).attr('id'),
                    navigation = document.querySelector('#${navId}'),
                    jumpTo = $(navigation).find(options.jumpToClass);

                let navheight = 0;
                navheight = setNavHeight(navigation);

                if (options.animate) {
                    animateOnScroll(jumpTo, navigation);
                }

                //  Attach year on scroll
                if (options.containers.length > 0) {
                    $(window).on("scroll", function () {
                        options.containers.each(function (index, element) {
                            let $years = (options.isMobile) ? $(navigation).find('.dropdown-item') : $(navigation).find('li'),
                                windowOffset = window.pageYOffset,
                                elementOffset = element.getBoundingClientRect().top + window.pageYOffset - 120,
                                elementHeight = elementOffset + element.offsetHeight + 30;

                            if (windowOffset >= elementOffset && windowOffset <= elementHeight) {
                                $years.removeClass('active');
                                $years.eq(index).addClass('active');

                                //  Update year into the dropdown button
                                if (options.isMobile) {
                                    options.dropdownBtn.text($years.eq(index).text());
                                }
                                return false;
                            } else {
                                $years.removeClass('active');
                            }
                        });
                    });
                }
            });
        }
    });
})(jQuery, window, document, undefined);






/*  --------------- MAIN JS --------------- */







$(document).ready(function () {


    const sidebar = $(".row-offcanvas");
    const toggleSidebarBtn = $(".toggle-hamburger-menu");
    const parent = $(".on").closest("ul");
    const caret = $(".on")
        .closest(".parent-nav-item")
        .find(".caret");
    caret.addClass("close-caret");

    parent.addClass("in");

    toggleSidebarBtn.click(function () {
        sidebar.toggleClass("active");
        toggleSidebarBtn.toggleClass("open");
    });

    //new header
    //Adding function below to collapse nav by default on INITIAL VIEW for mobile
    const flyOutMenuButtons = document.getElementsByClassName("nav-item-title");

    function alterClass() {
        var ww = document.body.clientWidth;
        var mobileSwitch = false; //This switch prevents the menu from auto-collapsing again on mobile when resizing the window
        var flyOutMenuButtons = document.getElementsByClassName("nav-item-title");
        var myURL = window.location.href;
        if ((myURL.indexOf(".com/employers") < 0) && (myURL.indexOf(".com/brokers") < 0)) {
            if ((ww < 768) && (!mobileSwitch)) {
                for (var i = 0; i < flyOutMenuButtons.length; i++) {
                    flyOutMenuButtons[i].classList.remove("active");
                }
                mobileSwitch = true;
            } else if ((ww >= 768)) {
                mobileSwitch = false;
                if ((!flyOutMenuButtons[0].classList.contains("active")) && (!flyOutMenuButtons[1].classList.contains("active")) && (!flyOutMenuButtons[2].classList.contains("active")) && (!flyOutMenuButtons[3].classList.contains("active"))) {
                    flyOutMenuButtons[0].classList.add("active");
                }
            }
        }
    }

    const headerHamburgerIcon = document.querySelector(".header-hamburger-menu");
    const headerMenu = document.querySelector(".main-nav");
    const headerMenuSubNav = document.querySelector(".sub-nav");
    headerHamburgerIcon.addEventListener("click", function () {
        headerHamburgerIcon.classList.toggle("open");
        headerMenu.classList.toggle("open");
        headerMenuSubNav.classList.toggle("open");
        alterClass();
    })


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


    //Toggle open menus for header fly out navigation

    for (var i = 0; i < flyOutMenuButtons.length; i++) {
        flyOutMenuButtons[i].addEventListener("click", function () {
            if (this.classList.contains("active")) {
                if (document.body.clientWidth < 768) {
                    this.classList.toggle("active");
                }
            } else {
                for (var i = 0; i < flyOutMenuButtons.length; i++) {
                    flyOutMenuButtons[i].classList.remove("active");
                }
                this.classList.toggle("active");
            }
        })
    }

    //removing the below because querySelectorAll doesn't seem to work in IE

    //Toggle open menus for header fly out navigation
    /*const flyOutMenuButtons = document.querySelectorAll(".nav-item-title");
    flyOutMenuButtons.forEach(function(el){
      el.addEventListener("click", function(){
        if(el.classList.contains('active')){
          el.classList.toggle("active");
        } else {
          document.querySelectorAll(".nav-item-title.active").forEach(function(elem) {
            elem.classList.remove("active");
          })
          el.classList.toggle("active");
        }
      })
    })*/



    const searchIcon = document.querySelector(".search-icon");
    searchIcon.addEventListener("click", function () {
        searchIcon.parentNode.parentNode.parentNode.classList.toggle("slide-out");
    })

    const closeIcon = document.querySelector(".close-icon")
    closeIcon.addEventListener("click", function () {
        searchIcon.parentNode.parentNode.parentNode.classList.remove("slide-out");
    })



    $(".nav-item").click(function () {
        $(this).find(".caret")
            .toggleClass("close-caret");
    });


    if ($('.component-edit-area').length) {

        $('.component-edit-area').each(function () {

            var $this = $(this),
                contentBlockName = $this.attr('data-content-block'),
                contentBlockHtml = $('#' + contentBlockName).html();

            $this.find('textarea').val(contentBlockHtml);

        });

        $('.btn-view-html').click(function (e) {
            e.preventDefault();

            var $this = $(this),
                textHtml = $this.siblings('textarea');

            if (textHtml.is(':hidden')) {
                textHtml.slideDown();
                $this.text('Hide HTML');
            } else {
                textHtml.slideUp();
                $this.text('View HTML');
            }

        });

        $('.btn-download-html').click(function (e) {
            e.preventDefault();

            var $this = $(this),
                contentBlockName = $this.parent('.component-edit-area').attr('data-content-block'),
                textareaBlock = $this.parent('.component-edit-area').find('textarea');
            try {
                var refId = textareaBlock.attr('id');
                saveTextAsFile(contentBlockName, refId);
            } catch (error) {
                throw error;
            }
        });

    }

    try {
        var cache = {
            'desktopNav': $("#history-timeline"),
            'mobileNav': $("#history-timeline-mobile"),
            'mqDesktop': window.matchMedia('(min-width: 1200px)'),
            'mqMobile': window.matchMedia('(max-width: 767px)'),
            'mqTablet': window.matchMedia('(min-device-width : 768px) and (max-device-width : 1024px)')
        };

        //  Apply when the timeline container exits
        if (cache.desktopNav && cache.mobileNav) {
            timeline({
                'containers': '.year-details',
                'main': '.timeline',
                'global': cache
            });
        }
    } catch (error) {
        console.warn(error);
    }

});

function saveTextAsFile(filename, textId) {
    var textToWrite = document.getElementById(textId).value;
    var textFileAsBlob = new Blob([textToWrite], {
        type: 'text/plain;charset=utf-8'
    });

    var downloadLink = document.createElement('a');
    downloadLink.download = filename + "-html.txt";
    //downloadLink.innerHTML = 'Download File';

    downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
    downloadLink.onclick = destroyClickedElement;
    downloadLink.style.display = 'none';
    downloadLink.dataset.downloadurl = ['text/plain', downloadLink.download, downloadLink.href].join(':');
    document.body.appendChild(downloadLink);


    downloadLink.click();

    return false;
}

function destroyClickedElement(event) {
    document.body.removeChild(event.target);
}

/**
 * Build timeline functionality
 * @param {Object} _config (DOM elements linked with the timeline)
 */
var timeline = function (_config) {
    let timelineContainer = (_config.global.mqMobile.matches) ? _config.global.mobileNav : _config.global.desktopNav;

    $(timelineContainer).BCBSTScrollSpy({
        animate: true,
        containers: $(".period-container"),
        dropdownBtn: $("#dropdownMenuButton"),
        isMobile: _config.global.mqMobile.matches
    });

    /* Check the location of each element */
    $(_config.main).find(_config.containers).each(function (i) {

        let bottom_of_object = $(this).offset().top + $(this).outerHeight()
        bottom_of_window = $(window).height();

        if (bottom_of_object > bottom_of_window) {
            $(this).addClass('hidden');
        }
    });

    $(window).scroll(function () {

        /* Check the location of each element hidden */
        $(_config.main).find('.hidden').each(function (i) {

            let bottom_of_object = $(this).offset().top + $(this).outerHeight(),
                bottom_of_window = $(window).scrollTop() + $(window).height() + timelineContainer.height();

            /* If the object is completely visible in the window, fadeIn it */
            if (bottom_of_window > bottom_of_object) {
                $(this).animate({
                    'opacity': '1'
                }, 700);
            }
        });
    });
};







/*  --------------- Prism JS --------------- */






/* http://prismjs.com/download.html?themes=prism&languages=markup+css+clike+javascript */
var _self = "undefined" != typeof window ? window : "undefined" != typeof WorkerGlobalScope && self instanceof WorkerGlobalScope ? self : {},
    Prism = function () {
        var e = /\blang(?:uage)?-(?!\*)(\w+)\b/i,
            t = _self.Prism = {
                util: {
                    encode: function (e) {
                        return e instanceof n ? new n(e.type, t.util.encode(e.content), e.alias) : "Array" === t.util.type(e) ? e.map(t.util.encode) : e.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/\u00a0/g, " ")
                    },
                    type: function (e) {
                        return Object.prototype.toString.call(e).match(/\[object (\w+)\]/)[1]
                    },
                    clone: function (e) {
                        var n = t.util.type(e);
                        switch (n) {
                            case "Object":
                                var a = {};
                                for (var r in e) e.hasOwnProperty(r) && (a[r] = t.util.clone(e[r]));
                                return a;
                            case "Array":
                                return e.map && e.map(function (e) {
                                    return t.util.clone(e)
                                })
                        }
                        return e
                    }
                },
                languages: {
                    extend: function (e, n) {
                        var a = t.util.clone(t.languages[e]);
                        for (var r in n) a[r] = n[r];
                        return a
                    },
                    insertBefore: function (e, n, a, r) {
                        r = r || t.languages;
                        var i = r[e];
                        if (2 == arguments.length) {
                            a = arguments[1];
                            for (var l in a) a.hasOwnProperty(l) && (i[l] = a[l]);
                            return i
                        }
                        var o = {};
                        for (var s in i)
                            if (i.hasOwnProperty(s)) {
                                if (s == n)
                                    for (var l in a) a.hasOwnProperty(l) && (o[l] = a[l]);
                                o[s] = i[s]
                            } return t.languages.DFS(t.languages, function (t, n) {
                            n === r[e] && t != e && (this[t] = o)
                        }), r[e] = o
                    },
                    DFS: function (e, n, a) {
                        for (var r in e) e.hasOwnProperty(r) && (n.call(e, r, e[r], a || r), "Object" === t.util.type(e[r]) ? t.languages.DFS(e[r], n) : "Array" === t.util.type(e[r]) && t.languages.DFS(e[r], n, r))
                    }
                },
                highlightAll: function (e, n) {
                    for (var a, r = document.querySelectorAll('code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code'), i = 0; a = r[i++];) t.highlightElement(a, e === !0, n)
                },
                highlightElement: function (a, r, i) {
                    for (var l, o, s = a; s && !e.test(s.className);) s = s.parentNode;
                    s && (l = (s.className.match(e) || [, ""])[1], o = t.languages[l]), a.className = a.className.replace(e, "").replace(/\s+/g, " ") + " language-" + l, s = a.parentNode, /pre/i.test(s.nodeName) && (s.className = s.className.replace(e, "").replace(/\s+/g, " ") + " language-" + l);
                    var u = a.textContent,
                        g = {
                            element: a,
                            language: l,
                            grammar: o,
                            code: u
                        };
                    if (!u || !o) return t.hooks.run("complete", g), void 0;
                    if (t.hooks.run("before-highlight", g), r && _self.Worker) {
                        var c = new Worker(t.filename);
                        c.onmessage = function (e) {
                            g.highlightedCode = n.stringify(JSON.parse(e.data), l), t.hooks.run("before-insert", g), g.element.innerHTML = g.highlightedCode, i && i.call(g.element), t.hooks.run("after-highlight", g), t.hooks.run("complete", g)
                        }, c.postMessage(JSON.stringify({
                            language: g.language,
                            code: g.code
                        }))
                    } else g.highlightedCode = t.highlight(g.code, g.grammar, g.language), t.hooks.run("before-insert", g), g.element.innerHTML = g.highlightedCode, i && i.call(a), t.hooks.run("after-highlight", g), t.hooks.run("complete", g)
                },
                highlight: function (e, a, r) {
                    var i = t.tokenize(e, a);
                    return n.stringify(t.util.encode(i), r)
                },
                tokenize: function (e, n) {
                    var a = t.Token,
                        r = [e],
                        i = n.rest;
                    if (i) {
                        for (var l in i) n[l] = i[l];
                        delete n.rest
                    }
                    e: for (var l in n)
                        if (n.hasOwnProperty(l) && n[l]) {
                            var o = n[l];
                            o = "Array" === t.util.type(o) ? o : [o];
                            for (var s = 0; s < o.length; ++s) {
                                var u = o[s],
                                    g = u.inside,
                                    c = !!u.lookbehind,
                                    f = 0,
                                    h = u.alias;
                                u = u.pattern || u;
                                for (var p = 0; p < r.length; p++) {
                                    var d = r[p];
                                    if (r.length > e.length) break e;
                                    if (!(d instanceof a)) {
                                        u.lastIndex = 0;
                                        var m = u.exec(d);
                                        if (m) {
                                            c && (f = m[1].length);
                                            var y = m.index - 1 + f,
                                                m = m[0].slice(f),
                                                v = m.length,
                                                k = y + v,
                                                b = d.slice(0, y + 1),
                                                w = d.slice(k + 1),
                                                N = [p, 1];
                                            b && N.push(b);
                                            var O = new a(l, g ? t.tokenize(m, g) : m, h);
                                            N.push(O), w && N.push(w), Array.prototype.splice.apply(r, N)
                                        }
                                    }
                                }
                            }
                        }
                    return r
                },
                hooks: {
                    all: {},
                    add: function (e, n) {
                        var a = t.hooks.all;
                        a[e] = a[e] || [], a[e].push(n)
                    },
                    run: function (e, n) {
                        var a = t.hooks.all[e];
                        if (a && a.length)
                            for (var r, i = 0; r = a[i++];) r(n)
                    }
                }
            },
            n = t.Token = function (e, t, n) {
                this.type = e, this.content = t, this.alias = n
            };
        if (n.stringify = function (e, a, r) {
                if ("string" == typeof e) return e;
                if ("Array" === t.util.type(e)) return e.map(function (t) {
                    return n.stringify(t, a, e)
                }).join("");
                var i = {
                    type: e.type,
                    content: n.stringify(e.content, a, r),
                    tag: "span",
                    classes: ["token", e.type],
                    attributes: {},
                    language: a,
                    parent: r
                };
                if ("comment" == i.type && (i.attributes.spellcheck = "true"), e.alias) {
                    var l = "Array" === t.util.type(e.alias) ? e.alias : [e.alias];
                    Array.prototype.push.apply(i.classes, l)
                }
                t.hooks.run("wrap", i);
                var o = "";
                for (var s in i.attributes) o += s + '="' + (i.attributes[s] || "") + '"';
                return "<" + i.tag + ' class="' + i.classes.join(" ") + '" ' + o + ">" + i.content + "</" + i.tag + ">"
            }, !_self.document) return _self.addEventListener ? (_self.addEventListener("message", function (e) {
            var n = JSON.parse(e.data),
                a = n.language,
                r = n.code;
            _self.postMessage(JSON.stringify(t.util.encode(t.tokenize(r, t.languages[a])))), _self.close()
        }, !1), _self.Prism) : _self.Prism;
        var a = document.getElementsByTagName("script");
        return a = a[a.length - 1], a && (t.filename = a.src, document.addEventListener && !a.hasAttribute("data-manual") && document.addEventListener("DOMContentLoaded", t.highlightAll)), _self.Prism
    }();
"undefined" != typeof module && module.exports && (module.exports = Prism);;
Prism.languages.markup = {
    comment: /<!--[\w\W]*?-->/,
    prolog: /<\?[\w\W]+?\?>/,
    doctype: /<!DOCTYPE[\w\W]+?>/,
    cdata: /<!\[CDATA\[[\w\W]*?]]>/i,
    tag: {
        pattern: /<\/?[^\s>\/]+(?:\s+[^\s>\/=]+(?:=(?:("|')(?:\\\1|\\?(?!\1)[\w\W])*\1|[^\s'">=]+))?)*\s*\/?>/i,
        inside: {
            tag: {
                pattern: /^<\/?[^\s>\/]+/i,
                inside: {
                    punctuation: /^<\/?/,
                    namespace: /^[^\s>\/:]+:/
                }
            },
            "attr-value": {
                pattern: /=(?:('|")[\w\W]*?(\1)|[^\s>]+)/i,
                inside: {
                    punctuation: /[=>"']/
                }
            },
            punctuation: /\/?>/,
            "attr-name": {
                pattern: /[^\s>\/]+/,
                inside: {
                    namespace: /^[^\s>\/:]+:/
                }
            }
        }
    },
    entity: /&#?[\da-z]{1,8};/i
}, Prism.hooks.add("wrap", function (t) {
    "entity" === t.type && (t.attributes.title = t.content.replace(/&amp;/, "&"))
});;
Prism.languages.css = {
    comment: /\/\*[\w\W]*?\*\//,
    atrule: {
        pattern: /@[\w-]+?.*?(;|(?=\s*\{))/i,
        inside: {
            rule: /@[\w-]+/
        }
    },
    url: /url\((?:(["'])(\\(?:\r\n|[\w\W])|(?!\1)[^\\\r\n])*\1|.*?)\)/i,
    selector: /[^\{\}\s][^\{\};]*?(?=\s*\{)/,
    string: /("|')(\\(?:\r\n|[\w\W])|(?!\1)[^\\\r\n])*\1/,
    property: /(\b|\B)[\w-]+(?=\s*:)/i,
    important: /\B!important\b/i,
    "function": /[-a-z0-9]+(?=\()/i,
    punctuation: /[(){};:]/
}, Prism.languages.css.atrule.inside.rest = Prism.util.clone(Prism.languages.css), Prism.languages.markup && (Prism.languages.insertBefore("markup", "tag", {
    style: {
        pattern: /<style[\w\W]*?>[\w\W]*?<\/style>/i,
        inside: {
            tag: {
                pattern: /<style[\w\W]*?>|<\/style>/i,
                inside: Prism.languages.markup.tag.inside
            },
            rest: Prism.languages.css
        },
        alias: "language-css"
    }
}), Prism.languages.insertBefore("inside", "attr-value", {
    "style-attr": {
        pattern: /\s*style=("|').*?\1/i,
        inside: {
            "attr-name": {
                pattern: /^\s*style/i,
                inside: Prism.languages.markup.tag.inside
            },
            punctuation: /^\s*=\s*['"]|['"]\s*$/,
            "attr-value": {
                pattern: /.+/i,
                inside: Prism.languages.css
            }
        },
        alias: "language-css"
    }
}, Prism.languages.markup.tag));;
Prism.languages.clike = {
    comment: [{
        pattern: /(^|[^\\])\/\*[\w\W]*?\*\//,
        lookbehind: !0
  }, {
        pattern: /(^|[^\\:])\/\/.*/,
        lookbehind: !0
  }],
    string: /("|')(\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,
    "class-name": {
        pattern: /((?:\b(?:class|interface|extends|implements|trait|instanceof|new)\s+)|(?:catch\s+\())[a-z0-9_\.\\]+/i,
        lookbehind: !0,
        inside: {
            punctuation: /(\.|\\)/
        }
    },
    keyword: /\b(if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/,
    "boolean": /\b(true|false)\b/,
    "function": /[a-z0-9_]+(?=\()/i,
    number: /\b-?(0x[\dA-Fa-f]+|\d*\.?\d+([Ee]-?\d+)?)\b/,
    operator: /--?|\+\+?|!=?=?|<=?|>=?|==?=?|&&?|\|\|?|\?|\*|\/|~|\^|%/,
    punctuation: /[{}[\];(),.:]/
};;
Prism.languages.javascript = Prism.languages.extend("clike", {
    keyword: /\b(as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|false|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|true|try|typeof|var|void|while|with|yield)\b/,
    number: /\b-?(0x[\dA-Fa-f]+|0b[01]+|0o[0-7]+|\d*\.?\d+([Ee][+-]?\d+)?|NaN|Infinity)\b/,
    "function": /(?!\d)[a-z0-9_$]+(?=\()/i
}), Prism.languages.insertBefore("javascript", "keyword", {
    regex: {
        pattern: /(^|[^/])\/(?!\/)(\[.+?]|\\.|[^/\\\r\n])+\/[gimyu]{0,5}(?=\s*($|[\r\n,.;})]))/,
        lookbehind: !0
    }
}), Prism.languages.insertBefore("javascript", "class-name", {
    "template-string": {
        pattern: /'(?:\\'|\\?[^'])*'/,
        inside: {
            interpolation: {
                pattern: /\$\{[^}]+\}/,
                inside: {
                    "interpolation-punctuation": {
                        pattern: /^\$\{|\}$/,
                        alias: "punctuation"
                    },
                    rest: Prism.languages.javascript
                }
            },
            string: /[\s\S]+/
        }
    }
}), Prism.languages.markup && Prism.languages.insertBefore("markup", "tag", {
    script: {
        pattern: /<script[\w\W]*?>[\w\W]*?<\/script>/i,
        inside: {
            tag: {
                pattern: /<script[\w\W]*?>|<\/script>/i,
                inside: Prism.languages.markup.tag.inside
            },
            rest: Prism.languages.javascript
        },
        alias: "language-javascript"
    }
});;






/*  --------------- KSS JS --------------- */





(function () {
    var KssStateGenerator;

    KssStateGenerator = (function () {
        var pseudo_selectors;

        pseudo_selectors = ['hover', 'enabled', 'disabled', 'active', 'visited', 'focus', 'target', 'checked', 'empty', 'first-of-type', 'last-of-type', 'first-child', 'last-child'];

        function KssStateGenerator() {
            var idx, idxs, pseudos, replaceRule, rule, stylesheet, _i, _len, _len2, _ref, _ref2;
            pseudos = new RegExp("(\\:" + (pseudo_selectors.join('|\\:')) + ")", "g");
            try {
                _ref = document.styleSheets;
                for (_i = 0, _len = _ref.length; _i < _len; _i++) {
                    stylesheet = _ref[_i];
                    if (stylesheet.href && stylesheet.href.indexOf(document.domain) >= 0) {
                        idxs = [];
                        _ref2 = stylesheet.cssRules;
                        for (idx = 0, _len2 = _ref2.length; idx < _len2; idx++) {
                            rule = _ref2[idx];
                            if ((rule.type === CSSRule.STYLE_RULE) && pseudos.test(rule.selectorText)) {
                                replaceRule = function (matched, stuff) {
                                    return matched.replace(/\:/g, '.pseudo-class-');
                                };
                                this.insertRule(rule.cssText.replace(pseudos, replaceRule));
                            }
                            pseudos.lastIndex = 0;
                        }
                    }
                }
            } catch (_error) {}
        }

        KssStateGenerator.prototype.insertRule = function (rule) {
            var headEl, styleEl;
            headEl = document.getElementsByTagName('head')[0];
            styleEl = document.createElement('style');
            styleEl.type = 'text/css';
            if (styleEl.styleSheet) {
                styleEl.styleSheet.cssText = rule;
            } else {
                styleEl.appendChild(document.createTextNode(rule));
            }
            return headEl.appendChild(styleEl);
        };

        return KssStateGenerator;

    })();

    new KssStateGenerator;

}).call(this);



// custom code.
(function () {


    // navigation.
    $('.kss-header__hamburger-trigger').on('click', function (e) {
        var kssNavigation = '.kss-navigation',
            kssDocumentation = '.kss-documentation',
            kssHamburger = '.kss-header__hamburger';

        if ($(kssNavigation).hasClass('kss-state-active')) {
            $(kssNavigation).removeClass('kss-state-active');
            $(kssDocumentation).removeClass('kss-state-active');
        } else {
            $(kssNavigation).addClass('kss-state-active');
            $(kssDocumentation).addClass('kss-state-active');
        }

        if ($(kssHamburger).hasClass('kss-state-active')) {
            $(kssHamburger).removeClass('kss-state-active');
        } else {
            $(kssHamburger).addClass('kss-state-active');
        }
    });


    // smooth scrolling.
    (function smoothScrolling() {
        $('.kss-nav__item > a[href*=section]').on('click', function (e) {
            if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
                var target = $(this.hash);
                target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');

                if (target.length) {
                    $('html, body').animate({
                        scrollTop: target.offset().top
                    }, 1000);

                    return false;
                }
            }
        });
    })();


    // colors.
    (function () {
        var parameters = $('.kss-parameters');

        if (parameters) {
            $('.kss-parameters__item').each(function (index) {
                var description = $(this).find('.kss-parameters__description').text().trim().replace(/; +/g, ';');
                var colorName = description.split(';')[1] ? description.split(';')[1] : '';
                var colorVar = $(this).find('.kss-parameters__name').text().trim();
                var colorCode = description.split(';')[0];
                var isHexadecimal = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(colorCode);
                var isRGB = /(rgba?\((?:\d{1,3}(, +|,|\))){3}(?:\d+\.\d+\))?)/i.test(colorCode);
                var colorContent = '<span class="kss-color__name">' + colorName + '</span>' +
                    '<span class="kss-color__var">' + colorVar + '</span>' +
                    '<span class="kss-color__code">' + colorCode + '</span>';

                if (isHexadecimal || isRGB) {
                    $(this).parent().addClass('kss-colors-container');
                    $(this).addClass('kss-color').css('background', colorCode);
                    $(this).find('.kss-parameters__description').html(colorContent);
                }
            });
        }
    })();


})();
/*           Registration        */
$(function () {
    // Modal functionality
    var $registrationSection = $('.registration-section');

    $registrationSection.each(function () {
        var $this = $(this);
        var $modalTriggerElement = $this.find('.registration-section-main-sample-link');
        var $modal = $this.find('.registration-section-modal');
        var $modalCloseButton = $modal.find('.registration-section-modal-close');

        function toggleModal() {
            $modal.toggleClass('registration-section-modal-visible');
        }

        $modalTriggerElement.on('click', toggleModal);
        $modalCloseButton.on('click', toggleModal);
    });
});
