/*******************************************************************************
 * Copyright 2018 Adobe
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/

/**
 * Element.matches()
 * https://developer.mozilla.org/enUS/docs/Web/API/Element/matches#Polyfill
 */
if (!Element.prototype.matches) {
    Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;
}

// eslint-disable-next-line valid-jsdoc
/**
 * Element.closest()
 * https://developer.mozilla.org/enUS/docs/Web/API/Element/closest#Polyfill
 */
if (!Element.prototype.closest) {
    Element.prototype.closest = function(s) {
        "use strict";
        var el = this;
        if (!document.documentElement.contains(el)) {
            return null;
        }
        do {
            if (el.matches(s)) {
                return el;
            }
            el = el.parentElement || el.parentNode;
        } while (el !== null && el.nodeType === 1);
        return null;
    };
}

/*******************************************************************************
 * Copyright 2018 Adobe
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
/* global
    CQ
 */
(function() {
    "use strict";

    var containerUtils = window.CQ && window.CQ.CoreComponents && window.CQ.CoreComponents.container && window.CQ.CoreComponents.container.utils ? window.CQ.CoreComponents.container.utils : undefined;
    if (!containerUtils) {
        // eslint-disable-next-line no-console
        console.warn("Tabs: container utilities at window.CQ.CoreComponents.container.utils are not available. This can lead to missing features. Ensure the core.wcm.components.commons.site.container client library is included on the page.");
    }
    var dataLayerEnabled;
    var dataLayer;
    var dataLayerName;

    var NS = "cmp";
    var IS = "tabs";

    var keyCodes = {
        END: 35,
        HOME: 36,
        ARROW_LEFT: 37,
        ARROW_UP: 38,
        ARROW_RIGHT: 39,
        ARROW_DOWN: 40
    };

    var selectors = {
        self: "[data-" + NS + '-is="' + IS + '"]',
        active: {
            tab: "cmp-tabs__tab--active",
            tabpanel: "cmp-tabs__tabpanel--active"
        }
    };

    /**
     * Tabs Configuration
     *
     * @typedef {Object} TabsConfig Represents a Tabs configuration
     * @property {HTMLElement} element The HTMLElement representing the Tabs
     * @property {Object} options The Tabs options
     */

    /**
     * Tabs
     *
     * @class Tabs
     * @classdesc An interactive Tabs component for navigating a list of tabs
     * @param {TabsConfig} config The Tabs configuration
     */
    function Tabs(config) {
        var that = this;

        if (config && config.element) {
            init(config);
        }

        /**
         * Initializes the Tabs
         *
         * @private
         * @param {TabsConfig} config The Tabs configuration
         */
        function init(config) {
            that._config = config;

            // prevents multiple initialization
            config.element.removeAttribute("data-" + NS + "-is");

            cacheElements(config.element);
            that._active = getActiveIndex(that._elements["tab"]);

            if (that._elements.tabpanel) {
                refreshActive();
                bindEvents();
                scrollToDeepLinkIdInTabs();
            }

            if (window.Granite && window.Granite.author && window.Granite.author.MessageChannel) {
                /*
                 * Editor message handling:
                 * - subscribe to "cmp.panelcontainer" message requests sent by the editor frame
                 * - check that the message data panel container type is correct and that the id (path) matches this specific Tabs component
                 * - if so, route the "navigate" operation to enact a navigation of the Tabs based on index data
                 */
                CQ.CoreComponents.MESSAGE_CHANNEL = CQ.CoreComponents.MESSAGE_CHANNEL || new window.Granite.author.MessageChannel("cqauthor", window);
                CQ.CoreComponents.MESSAGE_CHANNEL.subscribeRequestMessage("cmp.panelcontainer", function(message) {
                    if (message.data && message.data.type === "cmp-tabs" && message.data.id === that._elements.self.dataset["cmpPanelcontainerId"]) {
                        if (message.data.operation === "navigate") {
                            navigate(message.data.index);
                        }
                    }
                });
            }
        }

        /**
         * Displays the panel containing the element that corresponds to the deep link in the URI fragment
         * and scrolls the browser to this element.
         */
        function scrollToDeepLinkIdInTabs() {
            if (containerUtils) {
                var deepLinkItemIdx = containerUtils.getDeepLinkItemIdx(that, "tab", "tabpanel");
                if (deepLinkItemIdx > -1) {
                    var deepLinkItem = that._elements["tab"][deepLinkItemIdx];
                    if (deepLinkItem && that._elements["tab"][that._active].id !== deepLinkItem.id) {
                        navigateAndFocusTab(deepLinkItemIdx, true);
                    }
                    var hashId = window.location.hash.substring(1);
                    if (hashId) {
                        var hashItem = document.querySelector("[id='" + hashId + "']");
                        if (hashItem) {
                            hashItem.scrollIntoView();
                        }
                    }
                }
            }
        }

        /**
         * Returns the index of the active tab, if no tab is active returns 0
         *
         * @param {Array} tabs Tab elements
         * @returns {Number} Index of the active tab, 0 if none is active
         */
        function getActiveIndex(tabs) {
            if (tabs) {
                for (var i = 0; i < tabs.length; i++) {
                    if (tabs[i].classList.contains(selectors.active.tab)) {
                        return i;
                    }
                }
            }
            return 0;
        }

        /**
         * Caches the Tabs elements as defined via the {@code data-tabs-hook="ELEMENT_NAME"} markup API
         *
         * @private
         * @param {HTMLElement} wrapper The Tabs wrapper element
         */
        function cacheElements(wrapper) {
            that._elements = {};
            that._elements.self = wrapper;
            var hooks = that._elements.self.querySelectorAll("[data-" + NS + "-hook-" + IS + "]");

            for (var i = 0; i < hooks.length; i++) {
                var hook = hooks[i];
                if (hook.closest("." + NS + "-" + IS) === that._elements.self) { // only process own tab elements
                    var capitalized = IS;
                    capitalized = capitalized.charAt(0).toUpperCase() + capitalized.slice(1);
                    var key = hook.dataset[NS + "Hook" + capitalized];
                    if (that._elements[key]) {
                        if (!Array.isArray(that._elements[key])) {
                            var tmp = that._elements[key];
                            that._elements[key] = [tmp];
                        }
                        that._elements[key].push(hook);
                    } else {
                        that._elements[key] = hook;
                    }
                }
            }
        }

        /**
         * Binds Tabs event handling
         *
         * @private
         */
        function bindEvents() {
            window.addEventListener("hashchange", scrollToDeepLinkIdInTabs, false);
            var tabs = that._elements["tab"];
            if (tabs) {
                for (var i = 0; i < tabs.length; i++) {
                    (function(index) {
                        tabs[i].addEventListener("click", function(event) {
                            navigateAndFocusTab(index);
                        });
                        tabs[i].addEventListener("keydown", function(event) {
                            onKeyDown(event);
                        });
                    })(i);
                }
            }
        }

        /**
         * Handles tab keydown events
         *
         * @private
         * @param {Object} event The keydown event
         */
        function onKeyDown(event) {
            var index = that._active;
            var lastIndex = that._elements["tab"].length - 1;

            switch (event.keyCode) {
                case keyCodes.ARROW_LEFT:
                case keyCodes.ARROW_UP:
                    event.preventDefault();
                    if (index > 0) {
                        navigateAndFocusTab(index - 1);
                    }
                    break;
                case keyCodes.ARROW_RIGHT:
                case keyCodes.ARROW_DOWN:
                    event.preventDefault();
                    if (index < lastIndex) {
                        navigateAndFocusTab(index + 1);
                    }
                    break;
                case keyCodes.HOME:
                    event.preventDefault();
                    navigateAndFocusTab(0);
                    break;
                case keyCodes.END:
                    event.preventDefault();
                    navigateAndFocusTab(lastIndex);
                    break;
                default:
                    return;
            }
        }

        /**
         * Refreshes the tab markup based on the current {@code Tabs#_active} index
         *
         * @private
         */
        function refreshActive() {
            var tabpanels = that._elements["tabpanel"];
            var tabs = that._elements["tab"];

            if (tabpanels) {
                if (Array.isArray(tabpanels)) {
                    for (var i = 0; i < tabpanels.length; i++) {
                        if (i === parseInt(that._active)) {
                            tabpanels[i].classList.add(selectors.active.tabpanel);
                            tabpanels[i].removeAttribute("aria-hidden");
                            tabs[i].classList.add(selectors.active.tab);
                            tabs[i].setAttribute("aria-selected", true);
                            tabs[i].setAttribute("tabindex", "0");
                        } else {
                            tabpanels[i].classList.remove(selectors.active.tabpanel);
                            tabpanels[i].setAttribute("aria-hidden", true);
                            tabs[i].classList.remove(selectors.active.tab);
                            tabs[i].setAttribute("aria-selected", false);
                            tabs[i].setAttribute("tabindex", "-1");
                        }
                    }
                } else {
                    // only one tab
                    tabpanels.classList.add(selectors.active.tabpanel);
                    tabs.classList.add(selectors.active.tab);
                }
            }
        }

        /**
         * Focuses the element and prevents scrolling the element into view
         *
         * @param {HTMLElement} element Element to focus
         */
        function focusWithoutScroll(element) {
            var x = window.scrollX || window.pageXOffset;
            var y = window.scrollY || window.pageYOffset;
            element.focus();
            window.scrollTo(x, y);
        }

        /**
         * Navigates to the tab at the provided index
         *
         * @private
         * @param {Number} index The index of the tab to navigate to
         */
        function navigate(index) {
            that._active = index;
            refreshActive();
        }

        /**
         * Navigates to the item at the provided index and ensures the active tab gains focus
         *
         * @private
         * @param {Number} index The index of the item to navigate to
         * @param {Boolean} keepHash true to keep the hash in the URL, false to update it
         */
        function navigateAndFocusTab(index, keepHash) {
            var exActive = that._active;
            if (!keepHash && containerUtils) {
                containerUtils.updateUrlHash(that, "tab", index);
            }
            navigate(index);
            focusWithoutScroll(that._elements["tab"][index]);

            if (dataLayerEnabled) {

                var activeItem = getDataLayerId(that._elements.tabpanel[index]);
                var exActiveItem = getDataLayerId(that._elements.tabpanel[exActive]);

                dataLayer.push({
                    event: "cmp:show",
                    eventInfo: {
                        path: "component." + activeItem
                    }
                });

                dataLayer.push({
                    event: "cmp:hide",
                    eventInfo: {
                        path: "component." + exActiveItem
                    }
                });

                var tabsId = that._elements.self.id;
                var uploadPayload = { component: {} };
                uploadPayload.component[tabsId] = { shownItems: [activeItem] };

                var removePayload = { component: {} };
                removePayload.component[tabsId] = { shownItems: undefined };

                dataLayer.push(removePayload);
                dataLayer.push(uploadPayload);
            }
        }
    }

    /**
     * Reads options data from the Tabs wrapper element, defined via {@code data-cmp-*} data attributes
     *
     * @private
     * @param {HTMLElement} element The Tabs element to read options data from
     * @returns {Object} The options read from the component data attributes
     */
    function readData(element) {
        var data = element.dataset;
        var options = [];
        var capitalized = IS;
        capitalized = capitalized.charAt(0).toUpperCase() + capitalized.slice(1);
        var reserved = ["is", "hook" + capitalized];

        for (var key in data) {
            if (Object.prototype.hasOwnProperty.call(data, key)) {
                var value = data[key];

                if (key.indexOf(NS) === 0) {
                    key = key.slice(NS.length);
                    key = key.charAt(0).toLowerCase() + key.substring(1);

                    if (reserved.indexOf(key) === -1) {
                        options[key] = value;
                    }
                }
            }
        }

        return options;
    }

    /**
     * Parses the dataLayer string and returns the ID
     *
     * @private
     * @param {HTMLElement} item the accordion item
     * @returns {String} dataLayerId or undefined
     */
    function getDataLayerId(item) {
        if (item) {
            if (item.dataset.cmpDataLayer) {
                return Object.keys(JSON.parse(item.dataset.cmpDataLayer))[0];
            } else {
                return item.id;
            }
        }
        return null;
    }

    /**
     * Document ready handler and DOM mutation observers. Initializes Tabs components as necessary.
     *
     * @private
     */
    function onDocumentReady() {
        dataLayerEnabled = document.body.hasAttribute("data-cmp-data-layer-enabled");
        if (dataLayerEnabled) {
            dataLayerName = document.body.getAttribute("data-cmp-data-layer-name") || "adobeDataLayer";
            dataLayer = window[dataLayerName] = window[dataLayerName] || [];
        }

        var elements = document.querySelectorAll(selectors.self);
        for (var i = 0; i < elements.length; i++) {
            new Tabs({ element: elements[i], options: readData(elements[i]) });
        }

        var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
        var body = document.querySelector("body");
        var observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                // needed for IE
                var nodesArray = [].slice.call(mutation.addedNodes);
                if (nodesArray.length > 0) {
                    nodesArray.forEach(function(addedNode) {
                        if (addedNode.querySelectorAll) {
                            var elementsArray = [].slice.call(addedNode.querySelectorAll(selectors.self));
                            elementsArray.forEach(function(element) {
                                new Tabs({ element: element, options: readData(element) });
                            });
                        }
                    });
                }
            });
        });

        observer.observe(body, {
            subtree: true,
            childList: true,
            characterData: true
        });
    }

    if (document.readyState !== "loading") {
        onDocumentReady();
    } else {
        document.addEventListener("DOMContentLoaded", onDocumentReady);
    }

    if (containerUtils) {
        window.addEventListener("load", containerUtils.scrollToAnchor, false);
    }

}());

/*******************************************************************************
 * Copyright 2018 Adobe
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/

/**
 * Element.matches()
 * https://developer.mozilla.org/enUS/docs/Web/API/Element/matches#Polyfill
 */
if (!Element.prototype.matches) {
    Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;
}

// eslint-disable-next-line valid-jsdoc
/**
 * Element.closest()
 * https://developer.mozilla.org/enUS/docs/Web/API/Element/closest#Polyfill
 */
if (!Element.prototype.closest) {
    Element.prototype.closest = function(s) {
        "use strict";
        var el = this;
        if (!document.documentElement.contains(el)) {
            return null;
        }
        do {
            if (el.matches(s)) {
                return el;
            }
            el = el.parentElement || el.parentNode;
        } while (el !== null && el.nodeType === 1);
        return null;
    };
}

/*******************************************************************************
 * Copyright 2018 Adobe
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
/* global
    CQ
 */
(function() {
    "use strict";

    var containerUtils = window.CQ && window.CQ.CoreComponents && window.CQ.CoreComponents.container && window.CQ.CoreComponents.container.utils ? window.CQ.CoreComponents.container.utils : undefined;
    if (!containerUtils) {
        // eslint-disable-next-line no-console
        console.warn("Tabs: container utilities at window.CQ.CoreComponents.container.utils are not available. This can lead to missing features. Ensure the core.wcm.components.commons.site.container client library is included on the page.");
    }
    var dataLayerEnabled;
    var dataLayer;

    var NS = "cmp";
    var IS = "tabs";

    var keyCodes = {
        END: 35,
        HOME: 36,
        ARROW_LEFT: 37,
        ARROW_UP: 38,
        ARROW_RIGHT: 39,
        ARROW_DOWN: 40
    };

    var selectors = {
        self: "[data-" + NS + '-is="' + IS + '"]',
        active: {
            tab: "cmp-tabs__tab--active",
            tabpanel: "cmp-tabs__tabpanel--active"
        }
    };

    /**
     * Tabs Configuration
     *
     * @typedef {Object} TabsConfig Represents a Tabs configuration
     * @property {HTMLElement} element The HTMLElement representing the Tabs
     * @property {Object} options The Tabs options
     */

    /**
     * Tabs
     *
     * @class Tabs
     * @classdesc An interactive Tabs component for navigating a list of tabs
     * @param {TabsConfig} config The Tabs configuration
     */
    function Tabs(config) {
        var that = this;

        if (config && config.element) {
            init(config);
        }

        /**
         * Initializes the Tabs
         *
         * @private
         * @param {TabsConfig} config The Tabs configuration
         */
        function init(config) {
            that._config = config;

            // prevents multiple initialization
            config.element.removeAttribute("data-" + NS + "-is");

            cacheElements(config.element);
            that._active = getActiveIndex(that._elements["tab"]);

            if (that._elements.tabpanel) {
                refreshActive();
                bindEvents();
                scrollToDeepLinkIdInTabs();
            }

            if (window.Granite && window.Granite.author && window.Granite.author.MessageChannel) {
                /*
                 * Editor message handling:
                 * - subscribe to "cmp.panelcontainer" message requests sent by the editor frame
                 * - check that the message data panel container type is correct and that the id (path) matches this specific Tabs component
                 * - if so, route the "navigate" operation to enact a navigation of the Tabs based on index data
                 */
                CQ.CoreComponents.MESSAGE_CHANNEL = CQ.CoreComponents.MESSAGE_CHANNEL || new window.Granite.author.MessageChannel("cqauthor", window);
                CQ.CoreComponents.MESSAGE_CHANNEL.subscribeRequestMessage("cmp.panelcontainer", function(message) {
                    if (message.data && message.data.type === "cmp-tabs" && message.data.id === that._elements.self.dataset["cmpPanelcontainerId"]) {
                        if (message.data.operation === "navigate") {
                            navigate(message.data.index);
                        }
                    }
                });
            }
        }

        /**
         * Displays the panel containing the element that corresponds to the deep link in the URI fragment
         * and scrolls the browser to this element.
         */
        function scrollToDeepLinkIdInTabs() {
            if (containerUtils) {
                var deepLinkItemIdx = containerUtils.getDeepLinkItemIdx(that, "tab", "tabpanel");
                if (deepLinkItemIdx > -1) {
                    var deepLinkItem = that._elements["tab"][deepLinkItemIdx];
                    if (deepLinkItem && that._elements["tab"][that._active].id !== deepLinkItem.id) {
                        navigateAndFocusTab(deepLinkItemIdx, true);
                    }
                    var hashId = window.location.hash.substring(1);
                    if (hashId) {
                        var hashItem = document.querySelector("[id='" + hashId + "']");
                        if (hashItem) {
                            hashItem.scrollIntoView();
                        }
                    }
                }
            }
        }

        /**
         * Returns the index of the active tab, if no tab is active returns 0
         *
         * @param {Array} tabs Tab elements
         * @returns {Number} Index of the active tab, 0 if none is active
         */
        function getActiveIndex(tabs) {
            if (tabs) {
                for (var i = 0; i < tabs.length; i++) {
                    if (tabs[i].classList.contains(selectors.active.tab)) {
                        return i;
                    }
                }
            }
            return 0;
        }

        /**
         * Caches the Tabs elements as defined via the {@code data-tabs-hook="ELEMENT_NAME"} markup API
         *
         * @private
         * @param {HTMLElement} wrapper The Tabs wrapper element
         */
        function cacheElements(wrapper) {
            that._elements = {};
            that._elements.self = wrapper;
            var hooks = that._elements.self.querySelectorAll("[data-" + NS + "-hook-" + IS + "]");

            for (var i = 0; i < hooks.length; i++) {
                var hook = hooks[i];
                if (hook.closest("." + NS + "-" + IS) === that._elements.self) { // only process own tab elements
                    var capitalized = IS;
                    capitalized = capitalized.charAt(0).toUpperCase() + capitalized.slice(1);
                    var key = hook.dataset[NS + "Hook" + capitalized];
                    if (that._elements[key]) {
                        if (!Array.isArray(that._elements[key])) {
                            var tmp = that._elements[key];
                            that._elements[key] = [tmp];
                        }
                        that._elements[key].push(hook);
                    } else {
                        that._elements[key] = hook;
                    }
                }
            }
        }

        /**
         * Binds Tabs event handling
         *
         * @private
         */
        function bindEvents() {
            window.addEventListener("hashchange", scrollToDeepLinkIdInTabs, false);
            var tabs = that._elements["tab"];
            if (tabs) {
                for (var i = 0; i < tabs.length; i++) {
                    (function(index) {
                        tabs[i].addEventListener("click", function(event) {
                            navigateAndFocusTab(index);
                        });
                        tabs[i].addEventListener("keydown", function(event) {
                            onKeyDown(event);
                        });
                    })(i);
                }
            }
        }

        /**
         * Handles tab keydown events
         *
         * @private
         * @param {Object} event The keydown event
         */
        function onKeyDown(event) {
            var index = that._active;
            var lastIndex = that._elements["tab"].length - 1;

            switch (event.keyCode) {
                case keyCodes.ARROW_LEFT:
                case keyCodes.ARROW_UP:
                    event.preventDefault();
                    if (index > 0) {
                        navigateAndFocusTab(index - 1);
                    }
                    break;
                case keyCodes.ARROW_RIGHT:
                case keyCodes.ARROW_DOWN:
                    event.preventDefault();
                    if (index < lastIndex) {
                        navigateAndFocusTab(index + 1);
                    }
                    break;
                case keyCodes.HOME:
                    event.preventDefault();
                    navigateAndFocusTab(0);
                    break;
                case keyCodes.END:
                    event.preventDefault();
                    navigateAndFocusTab(lastIndex);
                    break;
                default:
                    return;
            }
        }

        /**
         * Refreshes the tab markup based on the current {@code Tabs#_active} index
         *
         * @private
         */
        function refreshActive() {
            var tabpanels = that._elements["tabpanel"];
            var tabs = that._elements["tab"];

            if (tabpanels) {
                if (Array.isArray(tabpanels)) {
                    for (var i = 0; i < tabpanels.length; i++) {
                        if (i === parseInt(that._active)) {
                            tabpanels[i].classList.add(selectors.active.tabpanel);
                            tabpanels[i].removeAttribute("aria-hidden");
                            tabs[i].classList.add(selectors.active.tab);
                            tabs[i].setAttribute("aria-selected", true);
                            tabs[i].setAttribute("tabindex", "0");
                        } else {
                            tabpanels[i].classList.remove(selectors.active.tabpanel);
                            tabpanels[i].setAttribute("aria-hidden", true);
                            tabs[i].classList.remove(selectors.active.tab);
                            tabs[i].setAttribute("aria-selected", false);
                            tabs[i].setAttribute("tabindex", "-1");
                        }
                    }
                } else {
                    // only one tab
                    tabpanels.classList.add(selectors.active.tabpanel);
                    tabs.classList.add(selectors.active.tab);
                }
            }
        }

        /**
         * Focuses the element and prevents scrolling the element into view
         *
         * @param {HTMLElement} element Element to focus
         */
        function focusWithoutScroll(element) {
            var x = window.scrollX || window.pageXOffset;
            var y = window.scrollY || window.pageYOffset;
            element.focus();
            window.scrollTo(x, y);
        }

        /**
         * Navigates to the tab at the provided index
         *
         * @private
         * @param {Number} index The index of the tab to navigate to
         */
        function navigate(index) {
            that._active = index;
            refreshActive();
        }

        /**
         * Navigates to the item at the provided index and ensures the active tab gains focus
         *
         * @private
         * @param {Number} index The index of the item to navigate to
         * @param {Boolean} keepHash true to keep the hash in the URL, false to update it
         */
        function navigateAndFocusTab(index, keepHash) {
            var exActive = that._active;
            if (!keepHash && containerUtils) {
                containerUtils.updateUrlHash(that, "tab", index);
            }
            navigate(index);
            focusWithoutScroll(that._elements["tab"][index]);

            if (dataLayerEnabled) {

                var activeItem = getDataLayerId(that._elements.tabpanel[index]);
                var exActiveItem = getDataLayerId(that._elements.tabpanel[exActive]);

                dataLayer.push({
                    event: "cmp:show",
                    eventInfo: {
                        path: "component." + activeItem
                    }
                });

                dataLayer.push({
                    event: "cmp:hide",
                    eventInfo: {
                        path: "component." + exActiveItem
                    }
                });

                var tabsId = that._elements.self.id;
                var uploadPayload = { component: {} };
                uploadPayload.component[tabsId] = { shownItems: [activeItem] };

                var removePayload = { component: {} };
                removePayload.component[tabsId] = { shownItems: undefined };

                dataLayer.push(removePayload);
                dataLayer.push(uploadPayload);
            }
        }
    }

    /**
     * Reads options data from the Tabs wrapper element, defined via {@code data-cmp-*} data attributes
     *
     * @private
     * @param {HTMLElement} element The Tabs element to read options data from
     * @returns {Object} The options read from the component data attributes
     */
    function readData(element) {
        var data = element.dataset;
        var options = [];
        var capitalized = IS;
        capitalized = capitalized.charAt(0).toUpperCase() + capitalized.slice(1);
        var reserved = ["is", "hook" + capitalized];

        for (var key in data) {
            if (Object.prototype.hasOwnProperty.call(data, key)) {
                var value = data[key];

                if (key.indexOf(NS) === 0) {
                    key = key.slice(NS.length);
                    key = key.charAt(0).toLowerCase() + key.substring(1);

                    if (reserved.indexOf(key) === -1) {
                        options[key] = value;
                    }
                }
            }
        }

        return options;
    }

    /**
     * Parses the dataLayer string and returns the ID
     *
     * @private
     * @param {HTMLElement} item the accordion item
     * @returns {String} dataLayerId or undefined
     */
    function getDataLayerId(item) {
        if (item) {
            if (item.dataset.cmpDataLayer) {
                return Object.keys(JSON.parse(item.dataset.cmpDataLayer))[0];
            } else {
                return item.id;
            }
        }
        return null;
    }

    /**
     * Document ready handler and DOM mutation observers. Initializes Tabs components as necessary.
     *
     * @private
     */
    function onDocumentReady() {
        dataLayerEnabled = document.body.hasAttribute("data-cmp-data-layer-enabled");
        dataLayer = (dataLayerEnabled) ? window.adobeDataLayer = window.adobeDataLayer || [] : undefined;

        var elements = document.querySelectorAll(selectors.self);
        for (var i = 0; i < elements.length; i++) {
            new Tabs({ element: elements[i], options: readData(elements[i]) });
        }

        var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
        var body = document.querySelector("body");
        var observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                // needed for IE
                var nodesArray = [].slice.call(mutation.addedNodes);
                if (nodesArray.length > 0) {
                    nodesArray.forEach(function(addedNode) {
                        if (addedNode.querySelectorAll) {
                            var elementsArray = [].slice.call(addedNode.querySelectorAll(selectors.self));
                            elementsArray.forEach(function(element) {
                                new Tabs({ element: element, options: readData(element) });
                            });
                        }
                    });
                }
            });
        });

        observer.observe(body, {
            subtree: true,
            childList: true,
            characterData: true
        });
    }

    if (document.readyState !== "loading") {
        onDocumentReady();
    } else {
        document.addEventListener("DOMContentLoaded", onDocumentReady);
    }

    if (containerUtils) {
        window.addEventListener("load", containerUtils.scrollToAnchor, false);
    }

}());


$(document).ready(function () {
	$('.banner_text').each(function (index) {
		$(this)
			.find('p')
			.text(function (index, currentText) {
				var maxLength = 340;
				if (currentText.length >= maxLength) {
					return currentText.length > maxLength
						? currentText.substr(0, maxLength - 1) + '...'
						: currentText;
				} else {
					console.log(currentText, 'currentText');
					return currentText;
				}
			});
	});
});

$(document).ready(function () {
	// click on hamberger menu
	$('.utility-nav-hamberger-icon').on('click', function () {
		$('.utilitynav-hamberger-menu').css('width', '35.2%');
		$('.utilitynav-hamberger-menu').css('top', $('.utility-nav')[0].offsetTop);
	});
	// click on close menu
	$('.utilitynav-hamberger-menu-closebtn').on('click', function () {
		$('.utilitynav-hamberger-menu').css('width', '0');
	});
	const accordion = document.querySelectorAll('.olam-accordion__item');
	for(let counter = 0; counter < accordion.length; counter++) {
		$('.olam-accordion__icon', accordion[counter]).on('click', function() {
			if($(this).closest('.olam-accordion__item').hasClass('olam-accordion__item--active')) {
				$(this).closest('.olam-accordion__item').removeClass('olam-accordion__item--active');
			} else {
				$(this).closest('.olam-accordion__item').addClass('olam-accordion__item--active');
			}
		});
	}
	$('.utility-nav-caret').on('click', function () {
		if ($(window).width() < 1024) {
			var parentElment = $(this).parent();
			parentElment.find('.utility-nav-desc-mobile:first').css('top', parentElment[0].offsetTop + 50);
			$('.megamenu-tier1-caret, .megamenu-tier1-desc-mobile').removeClass('megamenu-active');
			$('.megamenu-tier1-desc-mobile').addClass('hide');
			if (parentElment.find('.utility-nav-desc-mobile:first').hasClass('megamenu-active')) {
				$('.utility-nav-desc-mobile').removeClass('megamenu-active');
				$('.utility-nav-desc-mobile').addClass('hide');
				parentElment.find('.menu-arrow-right:first').addClass('megamenu-active');
				parentElment.find('.menu-arrow-down:first, .utility-nav-desc-mobile:first').removeClass('megamenu-active');
				parentElment.find('.utility-nav-desc-mobile:first,.menu-arrow-down:first').addClass('hide');
				parentElment.find('.menu-arrow-right:first').removeClass('hide');
			} else {
				$('.utility-nav-desc-mobile, .menu-arrow-down').removeClass('megamenu-active');
				$('.utility-nav-desc-mobile, .menu-arrow-down').addClass('hide');
				$('.menu-arrow-right').removeClass('hide');
				$('.menu-arrow-right').addClass('megamenu-active');
				parentElment.find('.menu-arrow-right:first').addClass('hide');
				parentElment.find('.menu-arrow-down:first, .utility-nav-desc-mobile:first').addClass('megamenu-active');
				parentElment.find('.utility-nav-desc-mobile:first, .menu-arrow-down:first').removeClass('hide');
				parentElment.find('.menu-arrow-right:first').removeClass('megamenu-active');
			}
		}
	});
});

$(document).ready(function () {
	$('.banner_carousel').slick({
		dots: true,
		infinite: true,
		autoplay: $('.banner_carousel').attr('data-auto-scroll') === 'true',
		autoplaySpeed: 5000,
		slidesToShow: 1,
		slidesToScroll: 1,
		cssEase: 'linear',
		arrows: true,
	});
	setCarouselDotsArrow();
});
$(window).resize(function () {
	if($('.banner_carousel').length)
		setCarouselDotsArrow();
})
function setCarouselDotsArrow() {
	//setTimeout(() => {  This line commented for decibel fix as this arrow function is only available on ES6
	setTimeout(function () {
		$('.banner_carousel').each((idx, element) => {
			const $parent = element;
			let prevArrowDiff = window.matchMedia('(max-width: 575px)').matches ? 30 : 22;
			let nextArrowDiff = 26;
			if ($('.slick-dots', $parent).length) {
				const dotsLeft = $('.slick-dots', $parent).position().left;
				$('.slick-prev', $parent).css('left', $('.slick-dots li:first-child', $parent).position().left + dotsLeft - prevArrowDiff);
				$('.slick-next', $parent).css('left', $('.slick-dots li:last-child', $parent).position().left + dotsLeft + nextArrowDiff);
			}
		});
	}, 500);
}

var isInfoPodWindowMobile = window.matchMedia('(max-width:575px)').matches;
$(document).ready(function() {
    if (isInfoPodWindowMobile) {
        infoPodInitializeSlick();
    }
})

$(window).on('resize', function(){
    if(isInfoPodWindowMobile){
        infoPodInitializeSlick();
    } else {
        $('.info-pod__mobile-carousel').slick('unslick');
    }
})

function infoPodInitializeSlick() {
    $('.info-pod__mobile-carousel').not('.slick-initialized').slick({
        dots: true,
        infinite: true,
        autoplay: $('.info-pod__mobile-carousel').attr('data-auto-scroll') === 'true',
		autoplaySpeed: 5000,
        slidesToShow: 1,
        slidesToScroll: 1,
        arrows: true,
    });
    infoPodSlickArrow();
}
function infoPodSlickArrow() {
    setTimeout(() => {
        $('.info-pod__mobile-carousel').each((idx, element) => {
            const $parent = element;
            if($('.slick-dots', $parent).length) {
                $('.slick-prev', $parent).css('left', $('.slick-dots li:first-child', $parent).position().left - 25);
                $('.slick-next', $parent).css('left', $('.slick-dots li:last-child', $parent).position().left + 22);
            }
        });
    }, 100);
}
$(document).ready(function() {
    let sidenavTopOffset = 0;
    if($('.side-nav')[0])
        sidenavTopOffset = $('.side-nav')[0].offsetTop;
    $(document).scroll(function(){
        if ($(document).scrollTop() >= sidenavTopOffset) {
            $('.side-nav').addClass('sticky');
            $('.olam-banner--parallex').addClass("olam-banner-sticky-menu")
        }
        else {
            $('.side-nav').removeClass('sticky');
            $('.olam-banner--parallex').removeClass("olam-banner-sticky-menu")
        } 
      });
});
$(document).ready(function () {
	const isInfoPodVariationHorizontal = $(".info-pod-slider.info-pod--horizontal").length;

	$('.info-pod-slider').not('.slick-initialized').slick({
		dots: true,
		infinite: true,
		autoplay: $('.info-pod-slider').attr('data-auto-scroll') === 'true',
		autoplaySpeed: 5000,
		slidesToShow: isInfoPodVariationHorizontal ? 2 : 3,
		slidesToScroll: isInfoPodVariationHorizontal ? 2 : 3,
		cssEase: 'linear',
		arrows: true,
		responsive: [
			{
				breakpoint: 992,
				settings: {
					slidesToShow: 1,
					slidesToScroll: 1,
				}
			}
		],
	});
	setInfoPodSliderArrow();
});
function setInfoPodSliderArrow() {
    setTimeout(() => {
        $('.info-pod-slider').each((idx, element) => {
            const $parent = element;
            if($('.slick-dots', $parent).length) {
                $('.slick-prev', $parent).css('left', $('.slick-dots li:first-child', $parent).position().left - 25);
                $('.slick-next', $parent).css('left', $('.slick-dots li:last-child', $parent).position().left + 22);
            }
        });
    }, 100);
}
$(window).on('resize orientationchange', function() {
	if($('.info-pod-slider').length)
	setInfoPodSliderArrow();
});
$(document).ready(function () {
	let productArray = [];
	let eventArray = [];
	let selectedFilters = {
		Product: '',
		EventType: '',
	};
	let $timeSensitiveCarousel;
	let $timeSensitiveSlickCache;
	//initializing Slick Carousel
	$timeSensitiveCarousel = $(
		'.time-sensitive .time-sensitive-container .time-sensitive-horizontal-card'
	)
		.not('.slick-initialized')
		.slick({
			dots: false,
			infinite: false,
			autoplay: false,
			prevArrow:
				'<button type="button" data-role="none" class="slick-prev slick-arrow" aria-label="Previous" role="button"></button>',
			nextArrow:
				'<button type="button" data-role="none" class="slick-next slick-arrow" aria-label="Next" role="button"></i></button>',
			autoplaySpeed: 5000,
			slidesToShow: 2,
			slidesToScroll: 1,
			cssEase: 'linear',
			arrows: true,
			responsive: [
				{
					breakpoint: 992,
					settings: {
						slidesToShow: 1,
						slidesToScroll: 1,
						arrows: true,
						dots: false,
					},
				},
			],
		});
	//Cloning Slick Slides into cache
	if ($timeSensitiveCarousel[0])
		$timeSensitiveSlickCache = $timeSensitiveCarousel[0].slick.$slides.clone(
			true,
			true
		);
	//Initializing Timeline
	setTimeline();
	setInactiveDatePosition();
	//Initializing Product and Event Type Filter Dropdown
	$(
		'.time-sensitive .time-sensitive-container .time-sensitive-horizontal-card .slick-list .slick-track .time-sensitive-card .time-sensitive-card-tag-date .time-sensitive-card-tag-container'
	).each(function (i, obj) {
		let productObj = JSON.parse(
			obj.querySelector('.time-sensitive-card-product-hdn').value
		);
		if (productArray.indexOf(productObj.class) == -1) {
			productArray.push(productObj.class);
			let productAnchorElement = document.createElement("a");
			productAnchorElement.setAttribute("class","time-sensitive-filter-product-item");
			productAnchorElement.setAttribute("href","#");
			productAnchorElement.setAttribute("data-value",productObj.class);
			productAnchorElement.appendChild(document.createTextNode(DOMPurify.sanitize(productObj.display)));
			let productListElement = document.createElement("li");
			productListElement.appendChild(DOMPurify.sanitize(productAnchorElement));
			document.querySelector(
				'.time-sensitive .time-sensitive-container .time-sensitive-upcoming-events .time-sensitive-filters .time-sensitive-filter-product .time-sensitive-filter-product-options'
			).appendChild(productListElement);
		}
		let eventObj = JSON.parse(
			obj.querySelector('.time-sensitive-card-eventType-hdn').value
		);
		if (eventArray.indexOf(eventObj.class) == -1) {
			eventArray.push(eventObj.class);
			let eventAnchorElement = document.createElement("a");
			eventAnchorElement.setAttribute("class","time-sensitive-filter-eventType-item");
			eventAnchorElement.setAttribute("href","#");
			eventAnchorElement.setAttribute("data-value",eventObj.class);
			eventAnchorElement.appendChild(document.createTextNode(eventObj.display));
			let eventListElement = document.createElement("li");
			eventListElement.appendChild(eventAnchorElement);
			document.querySelector(
				'.time-sensitive .time-sensitive-container .time-sensitive-upcoming-events .time-sensitive-filters .time-sensitive-filter-event_type .time-sensitive-filter-event_type-options'
			).appendChild(eventListElement);
		}
	});
	//Show hide Product Dropdown options
	$(
		'.time-sensitive .time-sensitive-container .time-sensitive-upcoming-events .time-sensitive-filters .time-sensitive-filter-product .time-sensitive-filter-product-btn'
	).on('click', function () {
		$(
			'.time-sensitive .time-sensitive-container .time-sensitive-upcoming-events .time-sensitive-filters .time-sensitive-filter-event_type .time-sensitive-filter-event_type-options'
		).css('display', 'none');
		if (
			$(
				'.time-sensitive .time-sensitive-container .time-sensitive-upcoming-events .time-sensitive-filters .time-sensitive-filter-product .time-sensitive-filter-product-options'
			).css('display') == 'block'
		) {
			$(
				'.time-sensitive .time-sensitive-container .time-sensitive-upcoming-events .time-sensitive-filters .time-sensitive-filter-product .time-sensitive-filter-product-options'
			).css('display', 'none');
		} else {
			$(
				'.time-sensitive .time-sensitive-container .time-sensitive-upcoming-events .time-sensitive-filters .time-sensitive-filter-product .time-sensitive-filter-product-options'
			).css('display', 'block');
		}
	});
	//Show hide Event Type Dropdown options
	$(
		'.time-sensitive .time-sensitive-container .time-sensitive-upcoming-events .time-sensitive-filters .time-sensitive-filter-event_type .time-sensitive-filter-event_type-btn'
	).on('click', function () {
		$(
			'.time-sensitive .time-sensitive-container .time-sensitive-upcoming-events .time-sensitive-filters .time-sensitive-filter-product .time-sensitive-filter-product-options'
		).css('display', 'none');
		if (
			$(
				'.time-sensitive .time-sensitive-container .time-sensitive-upcoming-events .time-sensitive-filters .time-sensitive-filter-event_type .time-sensitive-filter-event_type-options'
			).css('display') == 'block'
		) {
			$(
				'.time-sensitive .time-sensitive-container .time-sensitive-upcoming-events .time-sensitive-filters .time-sensitive-filter-event_type .time-sensitive-filter-event_type-options'
			).css('display', 'none');
		} else {
			$(
				'.time-sensitive .time-sensitive-container .time-sensitive-upcoming-events .time-sensitive-filters .time-sensitive-filter-event_type .time-sensitive-filter-event_type-options'
			).css('display', 'block');
		}
	});
	//Hiding dropdown options
	$(document).click(function () {
		$(
			'.time-sensitive .time-sensitive-container .time-sensitive-upcoming-events .time-sensitive-filters .time-sensitive-filter-product .time-sensitive-filter-product-options'
		).css('display', 'none');
		$(
			'.time-sensitive .time-sensitive-container .time-sensitive-upcoming-events .time-sensitive-filters .time-sensitive-filter-event_type .time-sensitive-filter-event_type-options'
		).css('display', 'none');
	});
	$(
		'.time-sensitive .time-sensitive-container .time-sensitive-upcoming-events .time-sensitive-filters .time-sensitive-filter-product'
	).click(function (e) {
		e.stopPropagation();
	});
	$(
		'.time-sensitive .time-sensitive-container .time-sensitive-upcoming-events .time-sensitive-filters .time-sensitive-filter-event_type'
	).click(function (e) {
		e.stopPropagation();
	});
	//Product filter on change
	$(
		'.time-sensitive .time-sensitive-container .time-sensitive-upcoming-events .time-sensitive-filters .time-sensitive-filter-product .time-sensitive-filter-product-options .time-sensitive-filter-product-item'
	).click(function (e) {
		$(
			'.time-sensitive .time-sensitive-container .time-sensitive-upcoming-events .time-sensitive-filters .time-sensitive-filter-product .time-sensitive-filter-product-btn .time-sensitive-filter-product-text'
		).text(e.currentTarget.innerText);
		$(
			'.time-sensitive .time-sensitive-container .time-sensitive-upcoming-events .time-sensitive-filters .time-sensitive-filter-product .time-sensitive-filter-product-options'
		).css('display', 'none');
		selectedFilters.Product = e.target.dataset.value;
		FilterTimeline();
	});
	//Event filter on change
	$(
		'.time-sensitive .time-sensitive-container .time-sensitive-upcoming-events .time-sensitive-filters .time-sensitive-filter-event_type .time-sensitive-filter-event_type-options .time-sensitive-filter-eventType-item'
	).click(function (e) {
		$(
			'.time-sensitive .time-sensitive-container .time-sensitive-upcoming-events .time-sensitive-filters .time-sensitive-filter-event_type .time-sensitive-filter-event_type-btn .time-sensitive-filter-event_type-text'
		).text(e.currentTarget.innerText);
		$(
			'.time-sensitive .time-sensitive-container .time-sensitive-upcoming-events .time-sensitive-filters .time-sensitive-filter-event_type .time-sensitive-filter-event_type-options'
		).css('display', 'none');
		selectedFilters.EventType = e.target.dataset.value;
		FilterTimeline();
	});
	//Slick carousel slide change
	$(
		'.time-sensitive .time-sensitive-container .time-sensitive-horizontal-card'
	).on('afterChange', function (event, slick, currentSlide, nextSlide) {
		setTimeline();
	});

	function FilterTimeline() {
		$timeSensitiveCarousel[0].slick.unload();
		$timeSensitiveCarousel[0].slick.$slideTrack
			.children($timeSensitiveCarousel[0].slick.options.slide)
			.remove();
		$timeSensitiveSlickCache.appendTo(
			$timeSensitiveCarousel[0].slick.$slideTrack
		);
		$timeSensitiveCarousel[0].slick.reinit();
		$timeSensitiveCarousel[0].slick.goTo(0);
		if (selectedFilters.Product != '') {
			$(
				'.time-sensitive .time-sensitive-container .time-sensitive-horizontal-card'
			).slick('slickFilter', function () {
				return $(selectedFilters.Product, this).length === 1;
			});
		}
		if (selectedFilters.EventType != '') {
			$(
				'.time-sensitive .time-sensitive-container .time-sensitive-horizontal-card'
			).slick('slickFilter', function () {
				return $(selectedFilters.EventType, this).length === 1;
			});
		}
	}

	function getOrdinal(day) {
		if (day === 1 || day === 21 || day === 31) return 'st';
		else if (day === 2 || day === 22) return 'nd';
		else return 'th';
	}

	function setTimeline() {
		if (
			$(
				'.time-sensitive .time-sensitive-container .time-sensitive-horizontal-card .slick-list .slick-track .slick-current .time-sensitive-card .time-sensitive-card-tag-date .time-sensitive-card-date-container .time-sensitive-card-date-text'
			)[0]
		) {
			let active_date = $(
				'.time-sensitive .time-sensitive-container .time-sensitive-horizontal-card .slick-list .slick-track .slick-current .time-sensitive-card .time-sensitive-card-tag-date .time-sensitive-card-date-container .time-sensitive-card-date-text'
			)[0].innerText;
			let active_day = parseInt(active_date.substring(0, 2), 10);
			$(
				'.time-sensitive .time-sensitive-container .time-sensitive-timeline .time-sensitive-horizontal-line .time-sensitive-horizontal-line-active-text .time-sensitive-horizontal-line-active-text-date'
			).text(active_day);
			$(
				'.time-sensitive .time-sensitive-container .time-sensitive-timeline .time-sensitive-horizontal-line .time-sensitive-horizontal-line-active-text .time-sensitive-horizontal-line-active-text-datesuffix'
			).text(getOrdinal(active_day));
			$(
				'.time-sensitive .time-sensitive-container .time-sensitive-timeline .time-sensitive-horizontal-line .time-sensitive-horizontal-line-active-text .time-sensitive-horizontal-line-active-text-monthyear'
			).text(active_date.substring(2));
			if (
				$(
					'.time-sensitive .time-sensitive-container .time-sensitive-horizontal-card .slick-list .slick-track .slick-current'
				)
					.next()
					.find(
						'.time-sensitive-card .time-sensitive-card-tag-date .time-sensitive-card-date-container .time-sensitive-card-date-text'
					)[0]
			)
				$(
					'.time-sensitive .time-sensitive-container .time-sensitive-timeline .time-sensitive-horizontal-line .time-sensitive-horizontal-line-inactive-text'
				).text(
					$(
						'.time-sensitive .time-sensitive-container .time-sensitive-horizontal-card .slick-list .slick-track .slick-current'
					)
						.next()
						.find(
							'.time-sensitive-card .time-sensitive-card-tag-date .time-sensitive-card-date-container .time-sensitive-card-date-text'
						)[0].innerText
				);
			$(
				'.time-sensitive .time-sensitive-container .time-sensitive-timeline .time-sensitive-horizontal-line .time-sensitive-horizontal-line-active-text'
			).css(
				'color',
				$(
					'.time-sensitive .time-sensitive-container .time-sensitive-horizontal-card .slick-list .slick-track .slick-current .time-sensitive-card .time-sensitive-card-tag-date .time-sensitive-card-date-container .time-sensitive-card-date-text'
				).css('color')
			);
			$(
				'.time-sensitive .time-sensitive-container .time-sensitive-timeline .time-sensitive-horizontal-line .time-sensitive-horizontal-line-circle-active-inner'
			).css(
				'background-color',
				$(
					'.time-sensitive .time-sensitive-container .time-sensitive-horizontal-card .slick-list .slick-track .slick-current .time-sensitive-card .time-sensitive-card-tag-date .time-sensitive-card-date-container .time-sensitive-card-date-text'
				).css('color')
			);
		}
	}
	$('.time-sensitive .time-sensitive-container .time-sensitive-horizontal-card')
		.not('.slick-initialized')
		.slick({
			prevArrow: $('.time-sensitive-horizontal-line-circle-inactive'),
		});
	$('.time-sensitive-horizontal-line-circle-inactive').click(function () {
		$('.time-sensitive-horizontal-card').slick('slickNext');
	});
	$('.time-sensitive-horizontal-line-circle-active-outer').click(function () {
		$('.time-sensitive-horizontal-card').slick('slickPrev');
	});
	for (let i = 0; i < $('.time-sensitive-card-date-text').length; i++) {
		let card = $('.time-sensitive-card-date-text')[i].innerText;
		let a = moment().format('DD MMM YYYY');
		var A = new Date(`${a}`);
		var card1 = new Date(`${card}`);
		if (moment(A).diff(card1, 'days') > 0) {
			$('.time-sensitive-horizontal-line-circle-inactive').trigger('click');
		} else {
			break;
		}
	}
});

$(window).resize(function () {
	if($('.time-sensitive').length)
	setInactiveDatePosition();
})
function setInactiveDatePosition() {
	setTimeout(() => {
		if ($(window).width() >= 992) {
			if ($('.time-sensitive .time-sensitive-container .time-sensitive-horizontal-card .slick-list .slick-track .slick-current').next())
			{
				$('.time-sensitive .time-sensitive-container .time-sensitive-timeline .time-sensitive-horizontal-line .time-sensitive-horizontal-line-circle-inactive').css(
					'left', $(window).width()/2
				);
				$('.time-sensitive .time-sensitive-container .time-sensitive-timeline .time-sensitive-horizontal-line .time-sensitive-horizontal-line-inactive-text').css(
					'left', $(window).width()/2
				);
			} else {
				$('.time-sensitive .time-sensitive-container .time-sensitive-timeline .time-sensitive-horizontal-line .time-sensitive-horizontal-line-circle-inactive').css(
					'display', 'none'
				);
				$('.time-sensitive .time-sensitive-container .time-sensitive-timeline .time-sensitive-horizontal-line .time-sensitive-horizontal-line-inactive-text').css(
					'display', 'none'
				);
			}
		}

	}, 0);
}


$(document).ready(function () {
	$('.testimonial_main_slider').not('.slick-initialized').slick({
		slidesToShow: 1,
		slidesToScroll: 1,
		arrows: false,
		fade: true,
		asNavFor: '.testimonial_slider',
	});
	$('.testimonial_slider')
		.not('.slick-initialized')
		.slick({
			dots: false,
			infinite: true,
			autoplay: false,
			autoplaySpeed: 5000,
			slidesToShow: 4,
			slidesToScroll: 1,
			cssEase: 'linear',
			arrows: true,
			focusOnSelect: true,
			asNavFor: '.testimonial_main_slider',
			responsive: [
				{
					breakpoint: 769,
					settings: {
						slidesToShow: 1,
						slidesToScroll: 1,
						arrows: true,
						dots: false,
					},
				},
				{
					breakpoint: 480,
					settings: {
						slidesToShow: 1,
						slidesToScroll: 1,
						arrows: true,
						dots: false,
					},
				},
			],
		});
});

$(document).ready(function () {
	$('.shareWidget').hover(
		function () {
			$(this).find('.share_widget').removeClass('hidden');
		},
		function () {
			$(this).find('.share_widget').addClass('hidden');
		}
	);
	$('.share_widget .linkedIn').click(function () {
		let url = $(this).attr('data-url');
		let shareURL =
			'https://www.linkedin.com/shareArticle?mini=true&url=' + url + '&amp;';
		window.open(shareURL, '_blank', 'height=485,width=700');
	});
	$('.share_widget .twitter').click(function () {
		let url = $(this).attr('data-url');
		let shareURL = 'https://twitter.com/intent/tweet?&url=' + url;
		window.open(shareURL, '_blank', 'height=485,width=700');
	});
});

$(document).ready(function () {
	let selectedType = 'All Pages';
	let searchTerm = '';
	let suggestedSearchObj = {};
	let itemOnDom = 0;
	let nomoreitems = false;
	let searchResultObj, newsAndEventsArr, renderedObjArr, Last3MonthArr, Last6MonthArr, Last12MonthArr, Last24MonthArr;
	let compName = $(".megamenu-container").attr("data-component");
	let searchApiUrl = $(".megamenu-container").attr("data-search-api-url");
	if (window.location.href.indexOf('search-results') === -1) {
		$('.megamenu-container .megamenu-main .search-area').addClass('hide');
		$('.megamenu-container .megamenu-mobile-main .search-area').addClass('hide');
        $('.megamenu-container .megamenu-mobile-main .megamenu-header-mobile').removeClass('hide');
		$('.megamenu-container .megamenu-main .search-icon-open').removeClass('hide');
		$('.megamenu-container .megamenu-main .megamenu-tier1').removeClass('hide');
    }
    else {
		$('.megamenu-container .megamenu-main .search-area').removeClass('hide');
		$('.megamenu-container .megamenu-mobile-main .search-area').removeClass('hide');
        $('.megamenu-container .megamenu-mobile-main .megamenu-header-mobile').addClass('hide');
		$('.megamenu-container .megamenu-main .search-icon-open').addClass('hide');
		$('.megamenu-container .megamenu-main .megamenu-tier1').addClass('hide');
		$('.megamenu-container .megamenu-main .search-area .search-box .search-input').val(decodeURI(window.location.search.substring(1).split('&')[0]));
		$('.megamenu-container .megamenu-mobile-main .search-area .search-box .search-input').val(decodeURI(window.location.search.substring(1).split('&')[0]));
		if($('.search_result_topsection')[0] != undefined) {
			suggestedSearchObj = JSON.parse($('.search_result_topsection')[0].dataset.searchsuggestion);
		}
		searchresultset();
	}
	function searchresultset() {
		$('.search_result_page .results').remove();
		if ($(window).width() >= 1024 && $('.megamenu-container .megamenu-main .search-area .search-box .search-input')[0].value.length != 0) {
			searchTerm = DOMPurify.sanitize($('.megamenu-container .megamenu-main .search-area .search-box .search-input').val());
		} else if ( $(window).width() < 1024 && 
					$('.megamenu-container .megamenu-mobile-main .search-area .search-box .search-input')[0].value.length != 0) {
			searchTerm = DOMPurify.sanitize($('.megamenu-container .megamenu-mobile-main .search-area .search-box .search-input').val());
		}
		$('.search_result_topsection .search_result_found .olam-header-h4').append("'" + searchTerm + "'");
		window.history.pushState({}, null, window.location.href.split('?')[0] + '?' + searchTerm);
		$('.search-autocomplete').addClass('hide');
		$.getJSON(searchApiUrl+'?searchString=' + searchTerm, function (result) {
			if(result.length > 0) {
				$('.search_result_topsection .search_result_found').removeClass('hide');
				$('.search_result_topsection .search_result_not_found').addClass('hide');
				$('.search_result_filters .search_result_filters-drpdwn').removeClass('hide');
				$('.search_result_filters .search_by_type').css('display','inline-block');
				nomoreitems = false
				itemOnDom = 0;
				searchResultObj = result;
				// renderedObjArr = result.filter(element => element.type != 'Documents');
				renderedObjArr = result;
				setPageDocFilter(searchResultObj, searchTerm);
				setTypeFilters(searchResultObj);
				setDateFilters(searchResultObj);
				// fillData();
				analyticsSuggestedSearchResult(compName,searchTerm, searchResultObj.length);
				setTimeout(function() {
					$('.search_result_filters .search_by_doc_or_page').change();
				}, 10);
			} else {
				searchResultObj = {};
				$('.search_result_topsection .search_result_found').addClass('hide');
				$('.search_result_topsection .search_result_not_found').removeClass('hide');
				$('.search_result_filters .search_result_filters-drpdwn').addClass('hide');
				$('.search_result_topsection .search_result_not_found .olam-header-h4').text('');
				$('.search_result_topsection .search_result_not_found .search-link').text('');
				$('.search_result_topsection .search_result_not_found .olam-header-h4').append("'" + searchTerm + "'. ");
				if(suggestedSearchObj[searchTerm]) {
					$('.search_result_topsection .search_result_not_found .search-link').append("'" + suggestedSearchObj[searchTerm] + "'");
					$('.search_result_topsection .search_result_not_found .search-suggestion').removeClass('hide');
				}
				else
					$('.search_result_topsection .search_result_not_found .search-suggestion').addClass('hide');
				$('.search_result_content .loading-item').hide();
				analyticsSuggestedSearchResult(compName,searchTerm, Object.entries(searchResultObj).length);
			}
		});
	}
	$('.search_result_topsection .search_result_not_found .search-link').on('click', function() {
		window.open(window.location.href.split('?')[0] + '?' + suggestedSearchObj[searchTerm], "_self");
	})
	function setPageDocFilter(searchResultObj) {
		let noPages = false;
		$('.search_result_filters .search_by_doc_or_page option').remove();
		if(searchResultObj.filter(element => element.type != 'Documents').length > 0) {
			$('.search_result_filters .search_by_doc_or_page').append('<option selected>Pages</option>');
		} else {
			noPages = true;
		}
		if(searchResultObj.filter(element => element.type == 'Documents').length > 0) {
			if(noPages) {
				$('.search_result_filters .search_by_doc_or_page').append('<option selected>Documents</option>');
			} else {
				$('.search_result_filters .search_by_doc_or_page').append('<option>Documents</option>');
			}
		}
	}
	function setTypeFilters(searchResultObj) {
		let searchTypeArr = []
		// $('.search_result_filters .search_result_filters-tabs .search_result_filters-tab').not(':first').remove();
		$('.search_result_filters .search_by_type option').not(':first').remove();
		searchResultObj.forEach(obj => {
			if(searchTypeArr.indexOf(obj.type) == -1) {
				searchTypeArr.push(obj.type);
			}
		});
		searchTypeArr.push(searchTypeArr.splice(searchTypeArr.indexOf('About Us'), 1)[0]);
		searchTypeArr.push(searchTypeArr.splice(searchTypeArr.indexOf('Products & Services'), 1)[0]);
		searchTypeArr.push(searchTypeArr.splice(searchTypeArr.indexOf('Sustainability'), 1)[0]);
		searchTypeArr.push(searchTypeArr.splice(searchTypeArr.indexOf('Investors'), 1)[0]);
		searchTypeArr.push(searchTypeArr.splice(searchTypeArr.indexOf('News & Events'), 1)[0]);
		searchTypeArr.push(searchTypeArr.splice(searchTypeArr.indexOf('Locations'), 1)[0]);
		searchTypeArr.splice(searchTypeArr.indexOf('Documents'), 1);
		// searchTypeArr.push(searchTypeArr.splice(searchTypeArr.indexOf('Documents'), 1)[0]);
		searchTypeArr.forEach(searchtype => {
			// $('.search_result_filters .search_result_filters-tabs ul').append('<li class="search_result_filters-tab olam-text-p5">' + searchtype + '</li>');
			$('.search_result_filters .search_by_type').append('<option>' + searchtype + '</option>');
		});
	}
	function setDateFilters(searchResultObj) {
		newsAndEventsArr = searchResultObj.filter(element => element.type === 'News & Events');
		Last3MonthArr = newsAndEventsArr.filter(element => moment(element.date, 'DD-MM-YYYY') >= moment().startOf('day').subtract(3,'month'));
		Last6MonthArr = newsAndEventsArr.filter(element => moment(element.date, 'DD-MM-YYYY') >= moment().startOf('day').subtract(6,'month'));
		Last12MonthArr = newsAndEventsArr.filter(element => moment(element.date, 'DD-MM-YYYY') >= moment().startOf('day').subtract(12,'month'));
		Last24MonthArr = newsAndEventsArr.filter(element => moment(element.date, 'DD-MM-YYYY') >= moment().startOf('day').subtract(24,'month'));
		$('.search_result_filters .search_by_date option').not(':first').remove();
		$('.search_result_filters .search_by_date').append('<option value=0>Last 3 months (' + Last3MonthArr.length + ')</option>');
		$('.search_result_filters .search_by_date').append('<option value=1>Last 6 months (' + Last6MonthArr.length + ')</option>');
		$('.search_result_filters .search_by_date').append('<option value=2>Last 12 months (' + Last12MonthArr.length + ')</option>');
		$('.search_result_filters .search_by_date').append('<option value=3>Last 24 months (' + Last24MonthArr.length + ')</option>');
	}
	$('.search_result_filters .search_by_doc_or_page').change(function () {
		$('.search_result_filters .search_by_type').val('Select type').change();
		$('.search_result_page .results').remove();
		let selectedDocOrPage = $('.search_result_filters .search_by_doc_or_page option:selected').val();
		if ('Pages' == selectedDocOrPage) {
			$('.search_result_filters .search_by_type').css('display','inline-block');
			renderedObjArr = searchResultObj.filter(element => element.type != 'Documents');
		} else {
			$('.search_result_filters .search_by_type').css('display', 'none');
			renderedObjArr = searchResultObj.filter(element => element.type == 'Documents');
		}
		nomoreitems = false;
		itemOnDom = 0;
		$('.search_result_content .loading-item').show();
		fillData();
	});
	// $(document).on('click', '.search_result_filters-tabs ul li.search_result_filters-tab', function() {
	// 	$('.search_result_filters-tab').removeClass('selected');
	// 	$(this).addClass('selected');
	// 	selectedType = this.innerText;
	// 	searchTypeChanged(selectedType);
	// })
	$('.search_result_filters .search_by_type').change(function () {
		searchTypeChanged($('.search_result_filters .search_by_type option:selected').val());
	});
	function searchTypeChanged(selectedSearchType) {
		$('.search_result_page .results').remove();
		if ('News & Events' == selectedSearchType) {
			$('.search_result_filters .search_by_date').css('display','inline-block');
		} else {
			$('.search_result_filters .search_by_date').css('display', 'none');
		}
		if(selectedSearchType == 'Select type' || selectedSearchType == 'All Pages') {
			renderedObjArr = searchResultObj.filter(element => element.type != 'Documents');
		} else {
			renderedObjArr = searchResultObj.filter(element => element.type == selectedSearchType);
		}
		nomoreitems = false;
		itemOnDom = 0;
		$('.search_result_content .loading-item').show();
		fillData();
	}
	$('.search_result_filters .search_by_date').change(function () {
		$('.search_result_page .results').remove();
		let arrayIndex = $('.search_result_filters .search_by_date option:selected').val();
		if (arrayIndex == 0) {
			renderedObjArr = Last3MonthArr;
		} else if (arrayIndex == 1) {
			renderedObjArr = Last6MonthArr;
		} else if (arrayIndex == 2) {
			renderedObjArr = Last12MonthArr;
		}  else if (arrayIndex == 3) {
			renderedObjArr = Last24MonthArr;
		} else {
			renderedObjArr = newsAndEventsArr;
		}
		nomoreitems = false;
		itemOnDom = 0;
		$('.search_result_content .loading-item').show();
		fillData();
	});
	function fillData() {
		let itemstobeloaded = 10;
		if(!nomoreitems) {
			if(renderedObjArr.length - itemOnDom <= 10){
				$('.search_result_content .loading-item').hide();
				nomoreitems = true;
				itemstobeloaded = renderedObjArr.length - itemOnDom;
			}
			for(let count = 0; count < itemstobeloaded; count++) {
				let iconType = renderedObjArr[itemOnDom + count].pageUrl.split('.')[1] == "pdf" ? '<i class="fa fa-file-pdf-o olam-text-p3" aria-hidden="true"></i>' :
								renderedObjArr[itemOnDom + count].pageUrl.split('.')[1] == "html" ? '<i class="fa fa-link olam-text-p3"></i>' :
																								'<i class="fa fa-file-archive-o olam-text-p3" aria-hidden="true"></i>';
				if (renderedObjArr[itemOnDom + count].description != undefined) {
					$('.search_result_page').append(
						'<div class="results">' +
							'<img class="lazy" src="' + renderedObjArr[itemOnDom + count].imgUrl + '">' + 
							'<div class="search-result__icon-container">'+ iconType + '</div>' +
							'<div class="result_content">' +
								'<div class="result_content_heading">' + 
									'<div class="olam-text-p3">' + 
										'<a href="' + renderedObjArr[itemOnDom + count].pageUrl + '">' + renderedObjArr[itemOnDom + count].pageTitle + '</a>' + 
									'</div>' + 
									'<p class="content_description olam-text-p5">' + renderedObjArr[itemOnDom + count].description +'</p>' + 
								'</div>' +
							'</div>' +
						'</div>'
					);
				} else {
					$('.search_result_page').append(
						'<div class="results">' +
							'<img src="' + renderedObjArr[itemOnDom + count].imgUrl + '">' +
							'<div class="search-result__icon-container">' + iconType + '</div>'+ 
							'<div class="result_content">' +
								'<div class="result_content_heading">' +
									'<div class="olam-text-p4">' +
										'<a href="' + renderedObjArr[itemOnDom + count].pageUrl + '">' +renderedObjArr[itemOnDom + count].pageTitle + '</a>' +
									'</div>' + 
								'</div>' +
							'</div>' +
						'</div>'
					);
				}
			}
			itemOnDom += itemstobeloaded;
		}	
	}
	function redirecttosearchresultpage(event) {
		$('.search_result_topsection .search_result_found .olam-header-h4').text('');
		var regex = /(\>|\<|\(|\)|\"|\'|\\|\/|\*|;|\:|\=|\{|\}|`|%|\+|\^|\!|\-)/g;
		if(regex.test($('.megamenu-container .megamenu-main .search-area .search-box .search-input')[0].value)) {
			$("#search-validate-error").css('display', 'block');
			event.preventDefault();
			return false;
		}
		else {
			$("#search-validate-error").css('display', 'none');
			if (window.location.href.indexOf('search-results') > -1) {
				searchresultset();
			} else {
				let serachResultPageURL = $('#search-path').length > 0 ?$('#search-path')[0].value : '/content/olamcorp/oil/uk/en/search-results.html';
				if ($(window).width() >= 1024 && $('.megamenu-container .megamenu-main .search-area .search-box .search-input')[0].value.length != 0) {
					window.open(serachResultPageURL + '?' + $('.megamenu-container .megamenu-main .search-area .search-box .search-input')[0].value);
					searchresultset();
				}
				else if ($(window).width() < 1024 &&
							$('.megamenu-container .megamenu-mobile-main .search-area .search-box .search-input')[0].value.length != 0) {
					window.open(serachResultPageURL + '?' + $('.megamenu-container .megamenu-mobile-main .search-area .search-box .search-input')[0].value);
					searchresultset();
				}
			}
		}
	}
	$('.megamenu-container .megamenu-main .search-area .search-box .search-input').on('keyup', function (e) {
		$("#search-validate-error").css('display', 'none');
		if (e.key === 'Enter') {
			redirecttosearchresultpage(e);
		} else if ($('.megamenu-container .megamenu-main .search-area .search-box .search-input')[0].value.length >= 3) {
			$.getJSON(searchApiUrl+'?limit=true&searchString=' + $('.megamenu-container .megamenu-main .search-area .search-box .search-input')[0].value,
				function (autocomplete_data) {
					$('.megamenu-container .megamenu-main .search-area .search-autocomplete')[0].innerHTML = '';
					$('.megamenu-container .megamenu-main .search-area .search-autocomplete').removeClass('hide');
					$('.megamenu-container .megamenu-main .search-area .search-autocomplete').css('top',$('.megamenu-container')[0].offsetTop +
							$('.megamenu-container')[0].offsetHeight);
					autocomplete_data.forEach((page) => {
						$('.megamenu-container .megamenu-main .search-area .search-autocomplete').append("<li><a class='search-autocomplete-item' href=" +
						DOMPurify.sanitize(encodeURI(page.pageUrl)) + '>' + DOMPurify.sanitize(page.pageTitle) + '</a></li>');
								
					});
					$('.megamenu-container .megamenu-main .search-area .search-autocomplete li').on('click', function(){
						let searchTermValue = $(this).text();
						analyticsSuggestedSearchTerm(compName, searchTermValue);
					});
				}
			);
		}
	});
	$('.megamenu-container .megamenu-main .search-area .search-box .search-icon').on('click', function (event) {
		redirecttosearchresultpage(event);
	});
	$('.megamenu-container .megamenu-mobile-main .search-area .search-box .search-input').on('keyup', function (e) {
		$("#search-validate-error").css('display', 'none');
		if (e.key === 'Enter') {
			redirecttosearchresultpage(e);
		} else if ($('.megamenu-container .megamenu-mobile-main .search-area .search-box .search-input')[0].value != undefined && 
						$('.megamenu-container .megamenu-mobile-main .search-area .search-box .search-input')[0].value.length >= 3) {
			$.getJSON(searchApiUrl+'?limit=true&searchString=' +
					$('.megamenu-container .megamenu-mobile-main .search-area .search-box .search-input')[0].value,
				function (autocomplete_data) {
					$('.megamenu-container .megamenu-mobile-main .search-area .search-autocomplete').removeClass('hide');
					$('.megamenu-container .megamenu-mobile-main .search-area .search-autocomplete')[0].innerHTML = '';
					$('.megamenu-container .megamenu-mobile-main .search-area .search-autocomplete').css(
						'top', $('.megamenu-container')[0].offsetTop + $('.megamenu-container')[0].offsetHeight
					);
					autocomplete_data.forEach((page) => {
						$('.megamenu-container .megamenu-mobile-main .search-area .search-autocomplete').append(
							"<li><a class='search-autocomplete-item' href=" + DOMPurify.sanitize(encodeURI(page.pageUrl)) + '>' + DOMPurify.sanitize(page.pageTitle) + '</a></li>');
					});
				}
			);
		}
	});
	$('.megamenu-container .megamenu-mobile-main .search-area .search-box .search-icon').on('click', function (event) {
		redirecttosearchresultpage(event);
	});
	$(document).on('click', '.search_result_page .results a', function(e){
			e.preventDefault();
			const clickedResultIndex = $(this).closest(".results").index() + 1;
			// const clickedEvent = $(this).text();
			const attribute = $(this).attr("target");
			const target = attribute ? attribute: "_self";
            const currentLink = $(this).attr("href");
			analyticsSearchClickThrough(compName, clickedResultIndex, function() {
				window.open(currentLink, target)
			});
	})
	
	

	window.onscroll = function () {
		if(searchResultObj != undefined && searchResultObj.length > 0) {
			setTimeout(function(){ 
				fillData();
			}, 500);
		}
	};
});
let isContactFormSubmitted = false;
let formName = $("#contactform").attr("name");
            let compName = $("#contactUsForm").attr("data-component");
            let eventName = $(".contact-banner__action-btn a").text();
$(".contact-banner__action-btn a").on("click", function(){
            analyticsFormStartEvent(formName, eventName, compName)
});

function contactRecaptchaCallback() {
    var v = grecaptcha.getResponse(window.contactWidgetId);
    if(v.length == 0){
        $("#contact_captcha_error").addClass("captchaError");
        document.getElementById('contact_captcha_error').style.display='block';
        return false;
    } else {
      $("#contact_captcha_error").removeClass("captchaError");
        document.getElementById('contact_captcha_error').style.display='none';
        return true;
    }
  }

$(function() {
  var spinner = $('#loader_contact');
  if($('#contact_popup').length > 0) {
  $.validator.addMethod(

    "regex",

    function(value, element, regexp) {


      if (regexp && regexp.constructor != RegExp) {

        regexp = new RegExp(regexp);
      } else if (regexp.global) regexp.lastIndex = 0;
      return this.optional(element) || regexp.test(value);
    }
  );

  $('#contact_popup').on('show.bs.modal', function(e) {
    if(e.relatedTarget.dataset.email && e.relatedTarget.dataset.email.length > 0 ) {
      $("#recipientEmail").val(e.relatedTarget.dataset.email);
    }
  });

  $("form[name='contactform']").on('submit', function(event) {
    event.preventDefault();
    return false;
  }).validate({
    rules: {
      firstName: {
        required: true,
        regex: /^[a-zA-Z0-9!?@#\$%£\"'\/\^\&*\)\(+=._-]+([a-zA-Z0-9\s!?@#\$%£\"'\/\^\&*\)\(+=._-]+)+$/
      },
      lastName: {
        required: true,
        regex: /^[a-zA-Z0-9!?@#\$%£\"'\/\^\&*\)\(+=._-]+([a-zA-Z0-9\s!?@#\$%£\"'\/\^\&*\)\(+=._-]+)+$/
      },
      subscribe: "required",
      company: {
        required: true,
        regex: /^[a-zA-Z0-9!?@#\$%£\"'\/\^\&*\)\(+=._-]+([a-zA-Z0-9\s!?@#\$%£\"'\/\^\&*\)\(+=._-]+)+$/
      },
      region: "required",
      contactNumber: {
        required: false,
        regex: /^[^<>]*$/
      },
      email: {
        required: true,
        email: true,
        regex: /^\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i
      },
      comments: {
        regex: /^[a-zA-Z0-9!?@#\$%£\"'\/\^\&*\)\(+=._-]+([a-zA-Z0-9\s,!?@#\$%£\"'\/\^\&*\)\(+=._-]+)+$/
      }
    },

    messages: {
      firstName: {
        required: "First Name is required",
        regex: "Please enter a valid First Name"
      },
      lastName: {
        required: "Last Name is required",
        regex: "Please enter a valid Last Name"
      },
      subscribe: "Please subscribe to proceed",
      company: {
        required: "Company is required",
        regex: "Please enter a valid Company Name"
      },
      region: "Please select region",

      contactNumber: {
        required: "This field is optional",
        regex: "Please enter a valid Contact Number"
      },
      email: {
        required: "Email is required",
        email: "Please enter a valid Email Address",
        regex: "Please enter a valid Email Address"
      },
      comments: {
        regex: "Please enter valid characters"
      }

    },

    highlight: function(element, errorClass, validClass) {
      if (!isContactFormSubmitted) return;
      $(element).parent('div.form-group').addClass(errorClass).removeClass(validClass);
    },
    unhighlight: function(element, errorClass, validClass) {
      if (!isContactFormSubmitted) return;
      $(element).parent('div.form-group').addClass(validClass).removeClass(errorClass);
    },


    submitHandler: function(form) {
      let errorCaptchaMsg = $("#contact_captcha_error").text().trim();
      const formInputsVal = {
                    "errorCode": "N/A",
                    "errorField": "Captcha",
                    "errorDescription": errorCaptchaMsg
                } 
      if(contactRecaptchaCallback()) {
    	  let subscribeArr = [];
          let subscribeCheckedItems = $('.subscribe-list :checkbox:checked');
          if( subscribeCheckedItems.length > 0) {
            for(let counter = 0; counter <  subscribeCheckedItems.length; counter++) {
              subscribeArr.push({'id' : subscribeCheckedItems[counter].id, 'value' : subscribeCheckedItems[counter].value});
            }
          }
        spinner.show();

        var data = {
          firstName: $('#firstName').val(),
          lastName: $('#lastName').val(),
          email: $('#email').val(),
          contactNumber: $('#contactNumber').val(),
          company: $('#company').val(),
          region: $("#region option:selected").text(),
          isExistingCustomer: $("#existingCustomer option:selected").text(),
          product: $("#product option:selected").text(),
          enquiredVolume: $("#enquiredVolume option:selected").text(),
          bagsFormat: $('.bagsformat:checked').val(),
          comments: $('#comments').val(),
          recipientEmail: $('#recipientEmail').val(),
          from: $('#fromEmail').val(),
          subscribe:  subscribeArr.length === 0 ? "" : JSON.stringify(subscribeArr)
        }
        var contactUsApiUrl = $("#contactUsForm").attr("data-contact-us-api-url");
        $.ajax({
          url: contactUsApiUrl,
          type: "POST",
          data: data,
          cache: false,
          success: function(response) {
        	if(response != ""){  
                //let resobj = JSON.parse(response);
                if(response.Failure != undefined && response.Failure.length > 0) {
                $('.success-modal-content').append('<p>' + DOMPurify.sanitize(response.Failure) + '</p>');
                analyticsFormCompleteEvent(formName, eventName, compName);
                }
                }
            spinner.hide();
            $('#contact_popup').modal("hide");
            $("#successModal").modal("show");
            document.getElementById('contactform').reset();
            $('div.form-group').removeClass("valid error");
            $('input.form-control-select').removeClass("blur_inputs");
            $('select.form-control-select').removeClass("blur_inputs");
          },

          error: function(response) {
            $("#dialog").html(DOMPurify.sanitize(response));
            analyticsFormCompleteEvent(formName, eventName, compName);
            spinner.hide();
            $('#contact_popup').modal("hide");
            $("#failureModal").modal("show");
            document.getElementById('contactform').reset();
            $('div.form-group').removeClass("valid error");
            $('input.form-control-select').removeClass("blur_inputs");
            $('select.form-control-select').removeClass("blur_inputs");

          }
        });
      }else{
        analyticsFormErrorEvent(compName, eventName, formInputsVal);
    }
    },
    invalidHandler: function(form, validator) {
      contactRecaptchaCallback();
      let formInputs = validator.errorList;
      if($("#contact_captcha_error").hasClass("captchaError")){
      let errorCaptchaMsg = $("#contact_captcha_error").text().trim();
          formInputs.push({message: errorCaptchaMsg, element: {name:"Captcha"}})
      }
      let formInputsVal = [];
      formInputs.forEach(function(ele) { 
          formInputsVal.push({
              "errorCode": "N/A",
              "errorField": ele.element.name,
              "errorDescription": ele.message
          })
        })
      
      analyticsFormErrorEvent(compName, eventName, formInputsVal);
          
},
    
  });
  }
});


function onInputEnter() {
  var inp = $("#firstName").val();
  if (jQuery.trim(inp).length > 0) {
    console.log("length is there***");
    $('input.form-control-select#firstName').addClass("blur_inputs");

  }
  var inp = $("#lastName").val();
  if (jQuery.trim(inp).length > 0) {
    console.log("length is lastName***");
    $('input.form-control-select#lastName').addClass("blur_inputs");

  }
  var inp = $("#email").val();
  if (jQuery.trim(inp).length > 0) {
    console.log("length is email***");
    $('input.form-control-select#email').addClass("blur_inputs");

  }
  var inp = $("#contactNumber").val();
  if (jQuery.trim(inp).length > 0) {
    console.log("length is contactNumber***");
    $('input.form-control-select#contactNumber').addClass("blur_inputs");

  }
  var inp = $("#company").val();
  if (jQuery.trim(inp).length > 0) {
    console.log("length is company***");
    $('input.form-control-select#company').addClass("blur_inputs");

  }
  var inp = $("#region").val();
  if (jQuery.trim(inp).length > 0) {
    console.log("length is region***");
    $('select.form-control-select#region').addClass("blur_inputs");

  }
  var inp = $("#existingCustomer").val();
  if (jQuery.trim(inp).length > 0) {
    console.log("length is existingCustomer***");
    $('select.form-control-select#existingCustomer').addClass("blur_inputs");

  }
  var inp = $("#product").val();
  if (jQuery.trim(inp).length > 0) {
    console.log("length is product***");
    $('select.form-control-select#product').addClass("blur_inputs");

  }
  var inp = $("#enquiredVolume").val();
  if (jQuery.trim(inp).length > 0) {
    console.log("length is enquiredVolume***");
    $('select.form-control-select#enquiredVolume').addClass("blur_inputs");

  }
  var inp = $("#comments").val();
  if (jQuery.trim(inp).length > 0) {
    console.log("length is comments***");
    $('textarea.form-control-select#comments').addClass("blur_inputs");

  }

}

$("form[name='contactform'] .send_btn").on('click', function(event) {
    isContactFormSubmitted = true;
});

$("form[name='contactform'] .form-control-select").on('blur', function(event) {
    onInputEnter();
});

$("form[name='contactform'] #contactNumber").on('blur', function(event) {
    onInputEnter();
});


function addRelatedArticleCarousel() {
	$(".olam-related-article__content")
		.not(".slick-initialized")
		.slick({
			dots: true,
			infinite: true,
			autoplay: $('.olam-related-article__content').attr('data-auto-scroll') === 'true',
			autoplaySpeed: 5000,
			slidesToShow: 4,
			slidesToScroll: 4,
			cssEase: "linear",
			arrows: true,
			responsive: [
				{
					breakpoint: 1600,
					settings: {
						slidesToShow: 3,
						slidesToScroll: 3
					},
				},
				{
					breakpoint: 992,
					settings: {
						slidesToShow: 2,
						slidesToScroll: 2
					}
				},
				{
					breakpoint: 768,
					settings: {
						slidesToShow: 1,
						slidesToScroll: 1
					}
				},
			],
		});
}


function setRelatedArticleCarouselSliderArrow() {
	setTimeout(() => {
		$(".olam-related-article .olam-related-article__content").each((idx, element) => {
			const $parent = element;
			if ($(".slick-dots", $parent).length) {
				$(".slick-prev", $parent).css(
					"left",
					$(".slick-dots li:first-child", $parent).position().left -
					25
				);
				$(".slick-next", $parent).css(
					"left",
					$(".slick-dots li:last-child", $parent).position().left + 22
				);
			}
		});
	}, 100);
}

function toggleSlickElements() {
	setTimeout(() => {
		if ($(".olam-related-article .olam-related-article__content .slick-dots").length) {
			$(".olam-related-article .olam-related-article__content .slick-list").css("paddingBottom", "30px");
		} else {
			$(".olam-related-article .olam-related-article__content .slick-list").css("paddingBottom", "0");
		}
	}, 100);
}

$(window).on('load resize orientationchange', function () {
	addRelatedArticleCarousel();
	setRelatedArticleCarouselSliderArrow();
	toggleSlickElements();
});



var isMobile = window.matchMedia('(max-width:1200px)').matches;
$(document).ready(function() {
    if (isMobile) {
        $(".olam-bod__tile--slider").each(function (index) {
            let element = $(this);
            initializeBODSlick(element);
        })
    }
})

$(window).on('resize', function(){
    if(isMobile){
        $(".olam-bod__tile--slider").each(function (index) {
            let element = $(this);
            initializeBODSlick(element);
        })
    } else {
        $('.olam-bod__tile--slider').slick('unslick'); 
    }
})

function initializeBODSlick(element) {    
    const tileLength = $('.olam-bod__tile', element).length;
    const maxDots = $(element).attr('data-max-dots');

    $(element).not('.slick-initialized').slick({
        dots: true,
        centerMode: true,
        infinite: true,
        autoplay: $(element).attr('data-auto-scroll') === 'true',
		autoplaySpeed: 5000,
        slidesToShow: 2,
        slidesToScroll: 2,
        arrows: true,
        responsive: [
            {
                 breakpoint: 768,
                 settings: {
                     slidesToShow: 1,
                     slidesToScroll: 1,
                     variableWidth: true,
                     dots: tileLength <= parseInt(maxDots)
                 }
             },
         ],
    });
    setBODSliderArrow(element);
}
function setBODSliderArrow(element) {
    setTimeout(() => {
        const $parent = element;
        if($('.slick-dots', $parent).length) {
            $('.slick-prev', $parent).css('left', $('.slick-dots li:first-child', $parent).position().left - 25);
            $('.slick-next', $parent).css('left', $('.slick-dots li:last-child', $parent).position().left + 22);
        }
    }, 100);
}
$(document).ready(function () {
	let megamenu_tier2_height = 0;
	let megamenu_tier3_height = 0;
	let megamenu_tier3_desc = 0;
	$('.search-icon-text').on('click', function () {
		$('.search-area').removeClass('hide');
		$('.megamenu-tier1').addClass('hide');
		$('.search-icon-open').addClass('hide');

		$('.megamenu-header-mobile').addClass('hide');
		$('.search-input').focus();
		if($('.search-input')[0])
		$('.search-input')[0].value = '';
		if($('.search-input')[1])
			$('.search-input')[1].value = '';
		$(
			'.megamenu-container .megamenu-mobile-main .search-area .search-autocomplete'
		).addClass('hide');
		$(
			'.megamenu-container .megamenu-main .search-area .search-autocomplete'
		).addClass('hide');
	});

	$('.search-area-close').on('click', function () {
		$('.search-area').addClass('hide');
		$('.megamenu-tier1').removeClass('hide');
		$('.search-icon-open').removeClass('hide');
		$("#search-validate-error").css('display', 'none');
		$('.megamenu-header-mobile').removeClass('hide');
	});

	$('.megamenu-hamberger-btn').on('click', function () {
		$('.megamenu-hamberger-menu-close').removeClass('hide');
		$('.megamenu-hamberger-btn').addClass('hide');
		$('.megamenu-desc-mobile').removeClass('hide');
		if ($('.utility-nav-mobile')) {
			$('.utility-nav-mobile').removeClass('hide');
			$('.megamenu-mobile-main').appendTo('.megamenu-utilitynav-wrapper');
			$('.utility-nav-mobile').appendTo('.megamenu-utilitynav-wrapper');
		}
	});

	$('.megamenu-hamberger-menu-close').on('click', function () {
		$('.megamenu-hamberger-menu-close').addClass('hide');
		$('.megamenu-tier1').removeClass('hide');

		$('.megamenu-hamberger-btn').removeClass('hide');
		$('.megamenu-desc-mobile').addClass('hide');
		$('.utility-nav-mobile').addClass('hide');
	});

	$('.megamenu-main').on('mouseleave', function () {
		$(
			'.megamenu-tier1-desc, .megamenu-tier2-desc, .megamenu-tier3-desc'
		).addClass('megamenu-hide');
		$('.megamenu-tier1-list-item').removeClass(
			'megamenu-tier1-list-item-selected'
		);
	});

	$('.megamenu-tier1-list-item').on('mouseover focus', function () {
		event.stopPropagation();
		if ($(window).width() >= 1024) {
			$('.megamenu-tier1-desc').css('top', $(this)[0].parentElement.parentElement.parentElement.offsetTop + $(this)[0].parentElement.parentElement.parentElement.offsetHeight);
			if($(this).find('.megamenu-tier2-desc').length == 0) {
				$(this).find('.megamenu-tier2').addClass('megamenu-tier2-without-submenu');
				$(this).find('.megamenu-tier2-list-item').addClass('megamenu-tier2-list-item-without-submenu');
			}
			$('.megamenu-tier1-list-item').removeClass(
				'megamenu-tier1-list-item-selected'
			);
			$('.megamenu-tier2-list-item').removeClass(
				'megamenu-tier2-list-item-selected'
			);
			$('.megamenu-tier3-list-item').removeClass(
				'megamenu-tier3-with4tier-list-item-selected'
			);
			$('.megamenu-tier3-list-item').removeClass(
				'megamenu-tier3-with3tier-list-item-selected'
			);
			$('.megamenu-tier2-list-title').removeClass(
				'megamenu-tier2-list-selected-title'
			);
			// $('.megamenu-tier3-list-text').removeClass(
			// 	'megamenu-tier3-list-selected-text'
			// );
			$('.megamenu-tier4-list-text').removeClass(
				'megamenu-tier4-list-selected-text'
			);
			$(
				'.megamenu-tier1-desc, .megamenu-tier2-desc, .megamenu-tier3-desc'
			).addClass('megamenu-hide');
			if (
				$(this)
					.find('.megamenu-tier1-desc:first')
					.find('.megamenu-tier2-list-item:first')
					.find('.megamenu-tier2-desc:first')
					.find('.megamenu-tier3-list-item:first')
					.find('div.megamenu-tier3-desc-with-4tiers').length !== 0
			) {
				$(this)
					.find('.megamenu-tier1-desc:first')
					.find('.megamenu-tier2-list-item:first')
					.find('.megamenu-tier2-desc:first')
					.find('.megamenu-tier3-list-item:first')
					.addClass('megamenu-tier3-with4tier-list-item-selected');
			} else if (
				$(this)
					.find('.megamenu-tier1-desc:first')
					.find('.megamenu-tier2-list-item:first')
					.find('.megamenu-tier2-desc:first')
					.find('.megamenu-tier3-list-item:first')
					.find('div.megamenu-tier3-desc-with-3tiers').length !== 0
			) {
				$(this)
					.find('.megamenu-tier1-desc:first')
					.find('.megamenu-tier2-list-item:first')
					.find('.megamenu-tier2-desc:first')
					.find('.megamenu-tier3-list-item:first')
					.addClass('megamenu-tier3-with3tier-list-item-selected');
			} 
			$(this)
				.addClass('megamenu-tier1-list-item-selected')
				.find('.megamenu-tier1-desc:first')
				.removeClass('megamenu-hide')
				.find('.megamenu-tier2-list-item:first')
				.addClass('megamenu-tier2-list-item-selected')
				.find('.megamenu-tier2-desc:first')
				.removeClass('megamenu-hide')
				.find('.megamenu-tier3-desc:first')
				.removeClass('megamenu-hide');
			$(this)
				.find('.megamenu-tier2-list-title:first')
				.addClass('megamenu-tier2-list-selected-title');
			// $(this)
			// 	.find('.megamenu-tier3-list-text:first')
			// 	.addClass('megamenu-tier3-list-selected-text');
			$(this)
				.find('.megamenu-tier4-list-text:first')
				.addClass('megamenu-tier4-list-selected-text');
			$(this).find('.megamenu-tier2:first').css('height', 'fit-content');
			$(this).find('.megamenu-tier3-wrapper:first').css('height', 'fit-content');
			$(this).find('.megamenu-tier3-desc:first').css('height', 'fit-content');
			megamenu_tier2_height = parseInt($(this).find('.megamenu-tier2:first').css('height').substring(0,3));
			megamenu_tier3_height = $(this).find('.megamenu-tier3-wrapper:first').length == 0 ? 0 : $(this).find('.megamenu-tier3-wrapper:first').css('height') == '0px' ? 0 : parseInt($(this).find('.megamenu-tier3-wrapper:first').css('height').substring(0,3));
			megamenu_tier3_desc = $(this).find('.megamenu-tier3-desc:first').length  == 0 ? 0 : $(this).find('.megamenu-tier3-desc:first').css('height') == '0px' ? 0 : parseInt($(this).find('.megamenu-tier3-desc:first').css('height').substring(0,3));
			let final_height = megamenu_tier2_height > megamenu_tier3_height ? megamenu_tier2_height > megamenu_tier3_desc ? megamenu_tier2_height : megamenu_tier3_desc :
								megamenu_tier3_height > megamenu_tier3_desc ? megamenu_tier3_height : megamenu_tier3_desc;
			$(this).find('.megamenu-tier2:first').css('height', final_height);
			if($(this).find('.megamenu-tier3-wrapper:first').length > 0)
			$(this).find('.megamenu-tier3-wrapper:first').css('height', final_height);
			if($(this).find('.megamenu-tier3-desc:first').length > 0)
			$(this).find('.megamenu-tier3-desc:first').css('height', final_height);
		}
	});

	$('.megamenu-tier2-list-item').on('mouseover focus', function (event) {
		event.stopPropagation();
		if ($(window).width() >= 1024) {
			$('.megamenu-tier2-list-item').removeClass(
				'megamenu-tier2-list-item-selected'
			);
			$('.megamenu-tier3-list-item').removeClass(
				'megamenu-tier3-with4tier-list-item-selected'
			);
			$('.megamenu-tier3-list-item').removeClass(
				'megamenu-tier3-with3tier-list-item-selected'
			);
			$('.megamenu-tier2-list-title').removeClass(
				'megamenu-tier2-list-selected-title'
			);
			// $('.megamenu-tier3-list-text').removeClass(
			// 	'megamenu-tier3-list-selected-text'
			// );
			$('.megamenu-tier4-list-text').removeClass(
				'megamenu-tier4-list-selected-text'
			);
			$('.megamenu-tier2-desc, .megamenu-tier3-desc').addClass(
				'megamenu-hide'
			);
			if (
				$(this)
					.find('.megamenu-tier2-desc:first')
					.find('.megamenu-tier3-list-item:first')
					.find('div.megamenu-tier3-desc-with-4tiers').length !== 0
			) {
				$(this)
					.find('.megamenu-tier2-desc:first')
					.find('.megamenu-tier3-list-item:first')
					.addClass('megamenu-tier3-with4tier-list-item-selected');
			} else if (
				$(this)
					.find('.megamenu-tier2-desc:first')
					.find('.megamenu-tier3-list-item:first')
					.find('div.megamenu-tier3-desc-with-3tiers').length !== 0
			) {
				$(this)
					.find('.megamenu-tier2-desc:first')
					.find('.megamenu-tier3-list-item:first')
					.addClass('megamenu-tier3-with3tier-list-item-selected');
			}
			if ($(this)
				.find('.megamenu-tier2-desc:first')
				.find('.megamenu-tier3-list-item:first')
				.hasClass('ofi')) {
					$(this)
						.find('.megamenu-tier2-desc:first')
						.find('.megamenu-tier3.megamenu-tier3-with-3tiers:first')
						.addClass('ofi');
					$(this)
						.find('.megamenu-tier2-desc:first')
						.find('.megamenu-tier3.megamenu-tier3-with-3tiers:first')
						.removeClass('oil');
					$(this)
						.find('.megamenu-tier2-desc:first')
						.find('.megamenu-tier3.megamenu-tier3-with-3tiers:first')
						.removeClass('oga');
				} else if ($(this)
				.find('.megamenu-tier2-desc:first')
				.find('.megamenu-tier3-list-item:first')
				.hasClass('oga')) {
					$(this)
						.find('.megamenu-tier2-desc:first')
						.find('.megamenu-tier3.megamenu-tier3-with-3tiers:first')
						.addClass('oga');
					$(this)
						.find('.megamenu-tier2-desc:first')
						.find('.megamenu-tier3.megamenu-tier3-with-3tiers:first')
						.removeClass('oil');
					$(this)
						.find('.megamenu-tier2-desc:first')
						.find('.megamenu-tier3.megamenu-tier3-with-3tiers:first')
						.removeClass('ofi');
				} else if ($(this)
				.find('.megamenu-tier2-desc:first')
				.find('.megamenu-tier3-list-item:first')
				.hasClass('oil')) {
					$(this)
						.find('.megamenu-tier2-desc:first')
						.find('.megamenu-tier3.megamenu-tier3-with-3tiers:first')
						.addClass('oil');
					$(this)
						.find('.megamenu-tier2-desc:first')
						.find('.megamenu-tier3.megamenu-tier3-with-3tiers:first')
						.removeClass('oga');
					$(this)
						.find('.megamenu-tier2-desc:first')
						.find('.megamenu-tier3.megamenu-tier3-with-3tiers:first')
						.removeClass('ofi');
				}
			$(this)
				.addClass('megamenu-tier2-list-item-selected')
				.find('.megamenu-tier2-desc:first')
				.removeClass('megamenu-hide')
				.find('.megamenu-tier3-desc:first')
				.removeClass('megamenu-hide');
			$(this)
				.find('.megamenu-tier2-list-title:first')
				.addClass('megamenu-tier2-list-selected-title');
			// $(this)
			// 	.find('.megamenu-tier3-list-text:first')
			// 	.addClass('megamenu-tier3-list-selected-text');
			$(this)
				.find('.megamenu-tier4-list-text:first')
				.addClass('megamenu-tier4-list-selected-text');
			$(this).find('.megamenu-tier3-wrapper:first').css('height', 'fit-content');
			$(this).find('.megamenu-tier3-desc:first').css('height', 'fit-content');
			megamenu_tier3_height = $(this).find('.megamenu-tier3-wrapper:first').length == 0 ? 0 : $(this).find('.megamenu-tier3-wrapper:first').css('height') == '0px' ? 0 : parseInt($(this).find('.megamenu-tier3-wrapper:first').css('height').substring(0,3));
			megamenu_tier3_desc = $(this).find('.megamenu-tier3-desc:first').length  == 0 ? 0 : $(this).find('.megamenu-tier3-desc:first').css('height') == '0px' ? 0 : parseInt($(this).find('.megamenu-tier3-desc:first').css('height').substring(0,3));
			let final_height = megamenu_tier2_height > megamenu_tier3_height ? megamenu_tier2_height > megamenu_tier3_desc ? megamenu_tier2_height : megamenu_tier3_desc :
								megamenu_tier3_height > megamenu_tier3_desc ? megamenu_tier3_height : megamenu_tier3_desc;
			$('.megamenu-tier2').css('height', final_height);
			if($(this).find('.megamenu-tier3-wrapper:first').length > 0)
			$(this).find('.megamenu-tier3-wrapper:first').css('height', final_height);
			if($(this).find('.megamenu-tier3-desc:first').length > 0)
			$(this).find('.megamenu-tier3-desc:first').css('height', final_height);
		}
	});

	$('.megamenu-tier3-list-item').on('mouseover focus', function (event) {
		event.stopPropagation();
		if ($(window).width() >= 1024) {
			$('.megamenu-tier3-list-item').removeClass(
				'megamenu-tier3-with4tier-list-item-selected'
			);
			$('.megamenu-tier3-list-item').removeClass(
				'megamenu-tier3-with3tier-list-item-selected'
			);
			// $('.megamenu-tier3-list-text').removeClass(
			// 	'megamenu-tier3-list-selected-text'
			// );
			$('.megamenu-tier4-list-text').removeClass(
				'megamenu-tier4-list-selected-text'
			);
			$('.megamenu-tier3-desc').addClass('megamenu-hide');
			if ($(this).find('div.megamenu-tier3-desc-with-4tiers').length !== 0) {
				$(this).addClass('megamenu-tier3-with4tier-list-item-selected');
			} else if ($(this).find('div.megamenu-tier3-desc-with-3tiers').length !== 0) {
				$(this).addClass('megamenu-tier3-with3tier-list-item-selected');
			}
			if($(this).hasClass('ofi')) {
				$(this).closest('.megamenu-tier3.megamenu-tier3-with-3tiers').removeClass('oga');
				$(this).closest('.megamenu-tier3.megamenu-tier3-with-3tiers').removeClass('oil');
				$(this).closest('.megamenu-tier3.megamenu-tier3-with-3tiers').addClass('ofi');
			} else if($(this).hasClass('oil')) {
				$(this).closest('.megamenu-tier3.megamenu-tier3-with-3tiers').removeClass('oga');
				$(this).closest('.megamenu-tier3.megamenu-tier3-with-3tiers').removeClass('ofi');
				$(this).closest('.megamenu-tier3.megamenu-tier3-with-3tiers').addClass('oil');
			} else if($(this).hasClass('oga')) {
				$(this).closest('.megamenu-tier3.megamenu-tier3-with-3tiers').removeClass('ofi');
				$(this).closest('.megamenu-tier3.megamenu-tier3-with-3tiers').removeClass('oil');
				$(this).closest('.megamenu-tier3.megamenu-tier3-with-3tiers').addClass('oga');
			} 
			$(this).find('.megamenu-tier3-desc:first').removeClass('megamenu-hide');
			// $(this)
			// 	.find('.megamenu-tier3-list-text:first')
			// 	.addClass('megamenu-tier3-list-selected-text');
			$(this)
				.find('.megamenu-tier4-list-text:first')
				.addClass('megamenu-tier4-list-selected-text');
			$(this).find('.megamenu-tier3-desc:first').css('height', 'fit-content');
			megamenu_tier3_desc = $(this).find('.megamenu-tier3-desc:first').length  == 0 ? 0 : $(this).find('.megamenu-tier3-desc:first').css('height') == '0px' ? 0 : parseInt($(this).find('.megamenu-tier3-desc:first').css('height').substring(0,3));
			let final_height = megamenu_tier2_height > megamenu_tier3_height ? megamenu_tier2_height > megamenu_tier3_desc ? megamenu_tier2_height : megamenu_tier3_desc :
								megamenu_tier3_height > megamenu_tier3_desc ? megamenu_tier3_height : megamenu_tier3_desc;
			$('.megamenu-tier2').css('height', final_height);
			if($('.megamenu-tier3-wrapper:first').length > 0)
			$('.megamenu-tier3-wrapper').css('height', final_height);
			if($(this).find('.megamenu-tier3-desc:first').length > 0)
			$(this).find('.megamenu-tier3-desc:first').css('height', final_height);
		}
	});

	$('.megamenu-tier4-list-item').on('mouseover focus', function (event) {
		event.stopPropagation();
		if ($(window).width() >= 1024) {
			$('.megamenu-tier4-list-text').removeClass(
				'megamenu-tier4-list-selected-text'
			);
			$(this)
				.find('.megamenu-tier4-list-text:first')
				.addClass('megamenu-tier4-list-selected-text');
		}
	});

	$('.megamenu-tier1-desc, .megamenu-tier2-desc, .megamenu-tier3-desc').on(
		'mouseover focus',
		function (event) {
			event.stopPropagation();
		}
	);

	$('.megamenu-tier1-caret').on('click', function () {
		if ($(window).width() < 1024) {
			$(this)
				.parent()
				.find('.megamenu-tier1-desc-mobile:first')
				.css('top', $(this).parent()[0].offsetTop + 50);
				$(
					'.utility-nav-caret, .utility-nav-desc-mobile'
				).removeClass('megamenu-active');
				$(
					'.utility-nav-desc-mobile'
				).addClass('hide');
			if (
				$(this)
					.parent()
					.find('.megamenu-tier1-desc-mobile:first')
					.hasClass('megamenu-active')
			) {
				$(
					'.megamenu-tier1-desc-mobile, .megamenu-tier2-desc-mobile, .megamenu-tier3-desc-mobile, .megamenu-tier4-desc-mobile'
				).removeClass('megamenu-active');
				$(
					'.megamenu-tier1-desc-mobile, .megamenu-tier2-desc-mobile, .megamenu-tier3-desc-mobile, .megamenu-tier4-desc-mobile'
				).addClass('hide');
				$(this)
					.parent()
					.find('.menu-arrow-right:first')
					.addClass('megamenu-active');
				$(this)
					.parent()
					.find('.menu-arrow-down:first')
					.removeClass('megamenu-active');
				$(this)
					.parent()
					.find('.megamenu-tier1-desc-mobile:first')
					.removeClass('megamenu-active');
				$(this)
					.parent()
					.find('.megamenu-tier1-desc-mobile:first')
					.addClass('hide');
				$(this).parent().find('.menu-arrow-right:first').removeClass('hide');
				$(this).parent().find('.menu-arrow-down:first').addClass('hide');
			} else {
				$(
					'.megamenu-tier1-desc-mobile, .megamenu-tier2-desc-mobile, .megamenu-tier3-desc-mobile, .megamenu-tier4-desc-mobile'
				).removeClass('megamenu-active');
				$(
					'.megamenu-tier1-desc-mobile, .megamenu-tier2-desc-mobile, .megamenu-tier3-desc-mobile, .megamenu-tier4-desc-mobile'
				).addClass('hide');
				$('.menu-arrow-right').removeClass('hide');
				$('.menu-arrow-right').addClass('megamenu-active');
				$('.menu-arrow-down').addClass('hide');
				$('.menu-arrow-down').removeClass('megamenu-active');
				$(this).parent().find('.menu-arrow-right:first').addClass('hide');
				$(this).parent().find('.menu-arrow-down:first').addClass('megamenu-active');
				$(this)
					.parent()
					.find('.megamenu-tier1-desc-mobile:first')
					.removeClass('hide');
				$(this)
					.parent()
					.find('.megamenu-tier1-desc-mobile:first')
					.addClass('megamenu-active');
				$(this)
					.parent()
					.find('.menu-arrow-right:first')
					.removeClass('megamenu-active');
				$(this).parent().find('.menu-arrow-down:first').removeClass('hide');
			}
		}
	});

	$('.megamenu-tier2-caret').on('click', function () {
		if ($(window).width() < 1024) {
			event.stopPropagation();
			$(this)
				.parent()
				.find('.megamenu-tier2-desc-mobile:first')
				.css('top', $(this).parent()[0].offsetTop + 40);
			if (
				$(this)
					.parent()
					.find('.megamenu-tier2-desc-mobile:first')
					.hasClass('megamenu-active')
			) {
				$(
					'.megamenu-tier2-desc-mobile, .megamenu-tier3-desc-mobile, .megamenu-tier4-desc-mobile'
				).removeClass('megamenu-active');
				$(
					'.megamenu-tier2-desc-mobile, .megamenu-tier3-desc-mobile, .megamenu-tier4-desc-mobile'
				).addClass('hide');
				$(this)
					.parent()
					.find('.menu-arrow-right:first')
					.addClass('megamenu-active');
				$(this)
					.parent()
					.find('.menu-arrow-down:first')
					.removeClass('megamenu-active');
				$(this)
					.parent()
					.find('.megamenu-tier2-desc-mobile:first')
					.removeClass('megamenu-active');
				$(this)
					.parent()
					.find('.megamenu-tier2-desc-mobile:first')
					.addClass('hide');
				$(this).parent().find('.menu-arrow-right:first').removeClass('hide');
				$(this).parent().find('.menu-arrow-down:first').addClass('hide');
			} else {
				$(
					'.megamenu-tier2-desc-mobile, .megamenu-tier3-desc-mobile, .megamenu-tier4-desc-mobile'
				).removeClass('megamenu-active');
				$(
					'.megamenu-tier2-desc-mobile, .megamenu-tier3-desc-mobile, .megamenu-tier4-desc-mobile'
				).addClass('hide');
				$(this).parent().parent().find('.menu-arrow-right').removeClass('hide');
				$(this)
					.parent()
					.parent()
					.find('.menu-arrow-right')
					.addClass('megamenu-active');
				$(this).parent().parent().find('.menu-arrow-down').addClass('hide');
				$(this)
					.parent()
					.parent()
					.find('.menu-arrow-down')
					.removeClass('megamenu-active');
				$(this).parent().find('.menu-arrow-right:first').addClass('hide');
				$(this).parent().find('.menu-arrow-down:first').addClass('megamenu-active');
				$(this)
					.parent()
					.find('.megamenu-tier2-desc-mobile:first')
					.removeClass('hide');
				$(this)
					.parent()
					.find('.megamenu-tier2-desc-mobile:first')
					.addClass('megamenu-active');
				$(this)
					.parent()
					.find('.menu-arrow-right:first')
					.removeClass('megamenu-active');
				$(this).parent().find('.menu-arrow-down:first').removeClass('hide');
			}
		}
	});
	$('.megamenu-tier3-caret').on('click', function () {
		if ($(window).width() < 1024) {
			$(this)
				.parent()
				.find('.megamenu-tier3-desc-mobile:first')
				.css('top', $(this).parent()[0].offsetTop + 40);
			event.stopPropagation();
			if (
				$(this)
					.parent()
					.find('.megamenu-tier3-desc-mobile:first')
					.hasClass('megamenu-active')
			) {
				$(
					'.megamenu-tier3-desc-mobile, .megamenu-tier4-desc-mobile'
				).removeClass('megamenu-active');
				$('.megamenu-tier3-desc-mobile, .megamenu-tier4-desc-mobile').addClass(
					'hide'
				);
				$(this)
					.parent()
					.find('.menu-arrow-right:first')
					.addClass('megamenu-active');
				$(this)
					.parent()
					.find('.menu-arrow-down:first')
					.removeClass('megamenu-active');
				$(this)
					.parent()
					.find('.megamenu-tier3-desc-mobile:first')
					.removeClass('megamenu-active');
				$(this)
					.parent()
					.find('.megamenu-tier3-desc-mobile:first')
					.addClass('hide');
				$(this).parent().find('.menu-arrow-right:first').removeClass('hide');
				$(this).parent().find('.menu-arrow-down:first').addClass('hide');
			} else {
				$(
					'.megamenu-tier3-desc-mobile, .megamenu-tier4-desc-mobile'
				).removeClass('megamenu-active');
				$('.megamenu-tier3-desc-mobile, .megamenu-tier4-desc-mobile').addClass(
					'hide'
				);
				$(this).parent().parent().find('.menu-arrow-right').removeClass('hide');
				$(this)
					.parent()
					.parent()
					.find('.menu-arrow-right')
					.addClass('megamenu-active');
				$(this).parent().parent().find('.menu-arrow-down').addClass('hide');
				$(this)
					.parent()
					.parent()
					.find('.menu-arrow-down')
					.removeClass('megamenu-active');
				$(this).parent().find('.menu-arrow-right:first').addClass('hide');
				$(this).parent().find('.menu-arrow-down:first').addClass('megamenu-active');
				$(this)
					.parent()
					.find('.megamenu-tier3-desc-mobile:first')
					.removeClass('hide');
				$(this)
					.parent()
					.find('.megamenu-tier3-desc-mobile:first')
					.addClass('megamenu-active');
				$(this)
					.parent()
					.find('.menu-arrow-right:first')
					.removeClass('megamenu-active');
				$(this).parent().find('.menu-arrow-down:first').removeClass('hide');
			}
		}
	});
	$(
		'.megamenu-tier1-item-container-mobile, .megamenu-tier2-item-mobile, .megamenu-tier3-item-mobile, .megamenu-tier4-item-mobile'
	).on('click', function () {
		if ($(window).width() < 1024) {
			event.stopPropagation();
		}
	});
});



$(document).ready(function() {
	$(".card-action-container .primary-button, .card-action-container .secondary-button, .card-action-container .tertiary-button").on("click",function() {
        const navigateTo = DOMPurify.sanitize($(this).attr('href').substring(1));
        if($(`[data-anchorId='${navigateTo}']`).length > 0) {
            let topPosition = 0;
            if($(".side-nav")[0].offsetTop == 0) {
                topPosition = $(`[data-anchorId='${DOMPurify.sanitize(navigateTo)}']`).position().top - $(".side-nav")[0].offsetHeight;
            } else {
                topPosition = $(`[data-anchorId='${DOMPurify.sanitize(navigateTo)}']`).position().top - (2 * $(".side-nav")[0].offsetHeight);
            }
            $("html, body").animate({
                "scrollTop": topPosition
            });
        }
	 });
 });
$(document).ready(function() {
    $(".card-action-container .secondary-button").on("click",function() {
        //const navigateTo = $(this).attr('href').substring(1); commented for decibel fix
        const navigateTo = DOMPurify.sanitize($(this).attr('href'));
        if($(`[data-anchorId='${navigateTo}']`).length > 0) {
            let topPosition = 0;
            if($(".side-nav")[0].offsetTop == 0) {
                topPosition = $(`[data-anchorId='${navigateTo}']`).position().top - $(".side-nav")[0].offsetHeight;
            } else {
                topPosition = $(`[data-anchorId='${navigateTo}']`).position().top - (2 * $(".side-nav")[0].offsetHeight);
            }
            $("html, body").animate({
                "scrollTop": topPosition
            });
        }
    });
});

$(document).ready(function(){
	$(".timeline-card:odd").addClass('timeline-card--reverse');
	for (let counter = 0; counter < $(".timeline-card--reverse").length; counter++) {
		if($(".timeline-card--reverse")[counter].querySelector('.timeline-card__img') == null) {
			$(".timeline-card--reverse")[counter].classList.add("timeline-card--reverse-without-image");
		}
	}
    $('.timeline-slider').not('.slick-initialized').slick({
		dots: true,
		infinite: true,
		autoplay: false,
		autoplaySpeed: 5000,
		slidesToShow: 4,
		slidesToScroll: 1,
		cssEase: 'linear',
		arrows: true,
		responsive: [
			{
				breakpoint: 769,
				settings: {
					slidesToShow: 1,
					slidesToScroll: 1,
				},
            },
            {
				breakpoint: 1201,
				settings: {
					slidesToShow: 2,
					slidesToScroll: 1,
					arrows: true,
					dots: true,
				},
            },
            {
				breakpoint: 1601,
				settings: {
					slidesToShow: 3,
					slidesToScroll: 1,
					arrows: true,
					dots: true,
				},
			},
		],
    });
	setTimelineCarouselDotsArrow();
	$(".timeline-card__wrapper .tertiary-button").on("click",function() {
		$('#timelineModal').modal('show');
		const $timeline_popup_header = $(this).closest(".timeline-card").find(".timeline-card__description-text").html();
		const $timeline_popup_img = $(this).closest(".timeline-card").find(".timeline-card__img").html();
		const $timeline_popup_content_header = $(this).closest(".timeline-card").find(".timeline-card__tooltip-header").html();
		const $timeline_popup_content_description = $(this).closest(".timeline-card").find(".timeline-card__tooltip-description").html();
		$(".timeline-popup").removeClass('oil');
		$(".timeline-popup").removeClass('ofi');
		$(".timeline-popup").removeClass('oga');
		if($(this).closest(".timeline-card").data('theme') == 'oil') {
			$(".timeline-popup").addClass('oil');
		}
		if($(this).closest(".timeline-card").data('theme') == 'ofi') {
			$(".timeline-popup").addClass('ofi');
		}
		if($(this).closest(".timeline-card").data('theme') == 'oga') {
			$(".timeline-popup").addClass('oga');
		}
		$(".timeline-popup .timeline-popup__header").empty();
		$(".timeline-popup .timeline-popup__header").append(DOMPurify.sanitize($timeline_popup_header));
		if($timeline_popup_img) {
			$(".timeline-popup").removeClass('timeline-popup__without-image');
			$(".timeline-popup .timeline-popup__image").css('display', 'block');
			$(".timeline-popup .timeline-popup__image").empty();
			$(".timeline-popup .timeline-popup__image").append(DOMPurify.sanitize($timeline_popup_img));
		} else {
			$(".timeline-popup").addClass('timeline-popup__without-image');
			$(".timeline-popup .timeline-popup__image").css('display', 'none');	
		}
		$(".timeline-popup .timeline-popup__content-header").empty();
		$(".timeline-popup .timeline-popup__content-header").append(DOMPurify.sanitize($timeline_popup_content_header));
		$(".timeline-popup .timeline-popup__content-description").empty();
		$(".timeline-popup .timeline-popup__content-description").append(DOMPurify.sanitize($timeline_popup_content_description));
		if($(this).closest(".timeline-card").data('popupbutton') == true) {
			$(".timeline-popup .timeline-popup__content a.secondary-button").attr("href", $(this).closest(".timeline-card").data('popupbuttonpath'));
			$(".timeline-popup .timeline-popup__content a.secondary-button").attr("target", $(this).closest(".timeline-card").data('popupbuttontarget'));
			$(".timeline-popup .timeline-popup__content a.secondary-button").empty();
			$(".timeline-popup .timeline-popup__content a.secondary-button").append(DOMPurify.sanitize($(this).closest(".timeline-card").data('popupbuttontext')));
			$(".timeline-popup .timeline-popup__content a.secondary-button").show();
		} else {
			$(".timeline-popup .timeline-popup__content a.secondary-button").hide();
		}
	 });
});
$(window).on('resize orientationchange', function() {
	if($('.timeline-slider').length)
	setTimelineCarouselDotsArrow();
});
function setTimelineCarouselDotsArrow() {
	setTimeout(() => {
		$('.timeline-slider').each((idx, element) => {
            const $parent = element;
            if($('.slick-dots', $parent).length) {
                $('.slick-prev', $parent).css('left', $('.slick-dots li:first-child', $parent).position().left - 30);
                $('.slick-next', $parent).css('left', $('.slick-dots li:last-child', $parent).position().left + 26);
            }
        });
	}, 100);
}
const countryList = [{
    "name": "Afghanistan",
    "value": "Afghanistan"
},{
    "name": "Albania",
    "value": "Albania"
},{
    "name": "Algeria",
    "value": "Algeria"
},{
    "name": "American Samoa",
    "value": "American Samoa"
},{
    "name": "Andorra",
    "value": "Andorra"
},{
    "name": "Angola",
    "value": "Angola"
},{
    "name": "Anguilla",
    "value": "Anguilla"
},{
    "name": "Antarctica",
    "value": "Antarctica"
},{
    "name": "Antigua And Barbuda",
    "value": "Antigua And Barbuda"
},{
    "name": "Argentina",
    "value": "Argentina"
},{
    "name": "Armenia",
    "value": "Armenia"
},{
    "name": "Aruba",
    "value": "Aruba"
},{
    "name": "Australia",
    "value": "Australia"
},{
    "name": "Austria",
    "value": "Austria"
},{
    "name": "Azerbaijan",
    "value": "Azerbaijan"
},{
    "name": "Bahamas",
    "value": "Bahamas"
},{
    "name": "Bahrain",
    "value": "Bahrain"
},{
    "name": "Bangladesh",
    "value": "Bangladesh"
},{
    "name": "Barbados",
    "value": "Barbados"
},{
    "name": "Belarus",
    "value": "Belarus"
},{
    "name": "Belgium",
    "value": "Belgium"
},{
    "name": "Belize",
    "value": "Belize"
},{
    "name": "Benin",
    "value": "Benin"
},{
    "name": "Bermuda",
    "value": "Bermuda"
},{
    "name": "Bhutan",
    "value": "Bhutan"
},{
    "name": "Bolivia",
    "value": "Bolivia"
},{
    "name": "Bosnia and Herzegovina",
    "value": "Bosnia and Herzegovina"
},{
    "name": "Botswana",
    "value": "Botswana"
},{
    "name": "Bouvet Island",
    "value": "Bouvet Island"
},{
    "name": "Brazil",
    "value": "Brazil"
},{
    "name": "British Indian Ocean Territory",
    "value": "British Indian Ocean Territory"
},{
    "name": "British Virgin Islands",
    "value": "British Virgin Islands"
},{
    "name": "Brunei",
    "value": "Brunei"
},{
    "name": "Bulgaria",
    "value": "Bulgaria"
},{
    "name": "Burkina Faso",
    "value": "Burkina Faso"
},{
    "name": "Burundi",
    "value": "Burundi"
},{
    "name": "Cambodia",
    "value": "Cambodia"
},{
    "name": "Cameroon",
    "value": "Cameroon"
},{
    "name": "Canada",
    "value": "Canada"
},{
    "name": "Cape Verde",
    "value": "Cape Verde"
},{
    "name": "Cayman Islands",
    "value": "Cayman Islands"
},{
    "name": "Central African Republic",
    "value": "Central African Republic"
},{
    "name": "Chad",
    "value": "Chad"
},{
    "name": "Chile",
    "value": "Chile"
},{
    "name": "China",
    "value": "China"
},{
    "name": "Christmas Island",
    "value": "Christmas Island"
},{
    "name": "Cocos [Keeling] Islands",
    "value": "Cocos [Keeling] Islands"
},{
    "name": "Colombia",
    "value": "Colombia"
},{
    "name": "Comoros",
    "value": "Comoros"
},{
    "name": "Congo [DRC]",
    "value": "Congo [DRC]"
},{
    "name": "Congo [Republic]",
    "value": "Congo [Republic]"
},{
    "name": "Cook Islands",
    "value": "Cook Islands"
},{
    "name": "Costa Rica",
    "value": "Costa Rica"
},{
    "name": "Cote d&#39;Ivoire",
    "value": "Cote d&#39;Ivoire"
},{
    "name": "Croatia",
    "value": "Croatia"
},{
    "name": "Cuba",
    "value": "Cuba"
},{
    "name": "Curacao",
    "value": "Curacao"
},{
    "name": "Cyprus",
    "value": "Cyprus"
},{
    "name": "Czech Republic",
    "value": "Czech Republic"
},{
    "name": "Denmark",
    "value": "Denmark"
},{
    "name": "Djibouti",
    "value": "Djibouti"
},{
    "name": "Dominica",
    "value": "Dominica"
},{
    "name": "Dominican Republic",
    "value": "Dominican Republic"
},{
    "name": "Ecuador",
    "value": "Ecuador"
},{
    "name": "Egypt",
    "value": "Egypt"
},{
    "name": "El Salvador",
    "value": "El Salvador"
},{
    "name": "Equatorial Guinea",
    "value": "Equatorial Guinea"
},{
    "name": "Eritrea",
    "value": "Eritrea"
},{
    "name": "Estonia",
    "value": "Estonia"
},{
    "name": "Ethiopia",
    "value": "Ethiopia"
},{
    "name": "Falkland Islands [Islas Malvinas]",
    "value": "Falkland Islands [Islas Malvinas]"
},{
    "name": "Faroe Islands",
    "value": "Faroe Islands"
},{
    "name": "Fiji",
    "value": "Fiji"
},{
    "name": "Finland",
    "value": "Finland"
},{
    "name": "France",
    "value": "France"
},{
    "name": "French Guiana",
    "value": "French Guiana"
},{
    "name": "French Polynesia",
    "value": "French Polynesia"
},{
    "name": "French Southern Territories",
    "value": "French Southern Territories"
},{
    "name": "Gabon",
    "value": "Gabon"
},{
    "name": "Gambia",
    "value": "Gambia"
},{
    "name": "Gaza Strip",
    "value": "Gaza Strip"
},{
    "name": "Georgia",
    "value": "Georgia"
},{
    "name": "Germany",
    "value": "Germany"
},{
    "name": "Ghana",
    "value": "Ghana"
},{
    "name": "Gibraltar",
    "value": "Gibraltar"
},{
    "name": "Greece",
    "value": "Greece"
},{
    "name": "Greenland",
    "value": "Greenland"
},{
    "name": "Grenada",
    "value": "Grenada"
},{
    "name": "Guadeloupe",
    "value": "Guadeloupe"
},{
    "name": "Guam",
    "value": "Guam"
},{
    "name": "Guatemala",
    "value": "Guatemala"
},{
    "name": "Guernsey",
    "value": "Guernsey"
},{
    "name": "Guinea",
    "value": "Guinea"
},{
    "name": "Guinea-Bissau",
    "value": "Guinea-Bissau"
},{
    "name": "Guyana",
    "value": "Guyana"
},{
    "name": "Haiti",
    "value": "Haiti"
},{
    "name": "Heard Island and McDonald Islands",
    "value": "Heard Island and McDonald Islands"
},{
    "name": "Honduras",
    "value": "Honduras"
},{
    "name": "Hong Kong",
    "value": "Hong Kong"
},{
    "name": "Hungary",
    "value": "Hungary"
},{
    "name": "Iceland",
    "value": "Iceland"
},{
    "name": "India",
    "value": "India"
},{
    "name": "Indonesia",
    "value": "Indonesia"
},{
    "name": "Iran",
    "value": "Iran"
},{
    "name": "Iraq",
    "value": "Iraq"
},{
    "name": "Ireland",
    "value": "Ireland"
},{
    "name": "Isle of Man",
    "value": "Isle of Man"
},{
    "name": "Israel",
    "value": "Israel"
},{
    "name": "Italy",
    "value": "Italy"
},{
    "name": "Jamaica",
    "value": "Jamaica"
},{
    "name": "Japan",
    "value": "Japan"
},{
    "name": "Jersey",
    "value": "Jersey"
},{
    "name": "Jordan",
    "value": "Jordan"
},{
    "name": "Kazakhstan",
    "value": "Kazakhstan"
},{
    "name": "Kenya",
    "value": "Kenya"
},{
    "name": "Kiribati",
    "value": "Kiribati"
},{
    "name": "Kosovo",
    "value": "Kosovo"
},{
    "name": "Kuwait",
    "value": "Kuwait"
},{
    "name": "Kyrgyzstan",
    "value": "Kyrgyzstan"
},{
    "name": "Laos",
    "value": "Laos"
},{
    "name": "Latvia",
    "value": "Latvia"
},{
    "name": "Lebanon",
    "value": "Lebanon"
},{
    "name": "Lesotho",
    "value": "Lesotho"
},{
    "name": "Liberia",
    "value": "Liberia"
},{
    "name": "Libya",
    "value": "Libya"
},{
    "name": "Liechtenstein",
    "value": "Liechtenstein"
},{
    "name": "Lithuania",
    "value": "Lithuania"
},{
    "name": "Luxembourg",
    "value": "Luxembourg"
},{
    "name": "Macau",
    "value": "Macau"
},{
    "name": "Macedonia [FYROM]",
    "value": "Macedonia [FYROM]"
},{
    "name": "Madagascar",
    "value": "Madagascar"
},{
    "name": "Malawi",
    "value": "Malawi"
},{
    "name": "Malaysia",
    "value": "Malaysia"
},{
    "name": "Maldives",
    "value": "Maldives"
},{
    "name": "Mali",
    "value": "Mali"
},{
    "name": "Malta",
    "value": "Malta"
},{
    "name": "Marshall Islands",
    "value": "Marshall Islands"
},{
    "name": "Martinique",
    "value": "Martinique"
},{
    "name": "Mauritania",
    "value": "Mauritania"
},{
    "name": "Mauritius",
    "value": "Mauritius"
},{
    "name": "Mayotte",
    "value": "Mayotte"
},{
    "name": "Mexico",
    "value": "Mexico"
},{
    "name": "Micronesia",
    "value": "Micronesia"
},{
    "name": "Moldova",
    "value": "Moldova"
},{
    "name": "Monaco",
    "value": "Monaco"
},{
    "name": "Mongolia",
    "value": "Mongolia"
},{
    "name": "Montenegro",
    "value": "Montenegro"
},{
    "name": "Montserrat",
    "value": "Montserrat"
},{
    "name": "Morocco",
    "value": "Morocco"
},{
    "name": "Mozambique",
    "value": "Mozambique"
},{
    "name": "Myanmar [Burma]",
    "value": "Myanmar [Burma]"
},{
    "name": "Namibia",
    "value": "Namibia"
},{
    "name": "Nauru",
    "value": "Nauru"
},{
    "name": "Nepal",
    "value": "Nepal"
},{
    "name": "Netherlands",
    "value": "Netherlands"
},{
    "name": "Netherlands Antilles",
    "value": "Netherlands Antilles"
},{
    "name": "New Caledonia",
    "value": "New Caledonia"
},{
    "name": "New Zealand",
    "value": "New Zealand"
},{
    "name": "Nicaragua",
    "value": "Nicaragua"
},{
    "name": "Niger",
    "value": "Niger"
},{
    "name": "Nigeria",
    "value": "Nigeria"
},{
    "name": "Niue",
    "value": "Niue"
},{
    "name": "Norfolk Island",
    "value": "Norfolk Island"
},{
    "name": "North Korea",
    "value": "North Korea"
},{
    "name": "Northern Mariana Islands",
    "value": "Northern Mariana Islands"
},{
    "name": "Norway",
    "value": "Norway"
},{
    "name": "Oman",
    "value": "Oman"
},{
    "name": "Pakistan",
    "value": "Pakistan"
},{
    "name": "Palau",
    "value": "Palau"
},{
    "name": "Palestinian Territories",
    "value": "Palestinian Territories"
},{
    "name": "Panama",
    "value": "Panama"
},{
    "name": "Papua New Guinea",
    "value": "Papua New Guinea"
},{
    "name": "Paraguay",
    "value": "Paraguay"
},{
    "name": "Peru",
    "value": "Peru"
},{
    "name": "Philippines",
    "value": "Philippines"
},{
    "name": "Pitcairn Islands",
    "value": "Pitcairn Islands"
},{
    "name": "Poland",
    "value": "Poland"
},{
    "name": "Portugal",
    "value": "Portugal"
},{
    "name": "Puerto Rico",
    "value": "Puerto Rico"
},{
    "name": "Qatar",
    "value": "Qatar"
},{
    "name": "Réunion",
    "value": "Réunion"
},{
    "name": "Romania",
    "value": "Romania"
},{
    "name": "Russia",
    "value": "Russia"
},{
    "name": "Rwanda",
    "value": "Rwanda"
},{
    "name": "Saint Helena",
    "value": "Saint Helena"
},{
    "name": "Saint Kitts and Nevis",
    "value": "Saint Kitts and Nevis"
},{
    "name": "Saint Lucia",
    "value": "Saint Lucia"
},{
    "name": "Saint Pierre and Miquelon",
    "value": "Saint Pierre and Miquelon"
},{
    "name": "Saint Vincent and the Grenadines",
    "value": "Saint Vincent and the Grenadines"
},{
    "name": "Samoa",
    "value": "Samoa"
},{
    "name": "San Marino",
    "value": "San Marino"
},{
    "name": "São Tomé and Príncipe",
    "value": "São Tomé and Príncipe"
},{
    "name": "Saudi Arabia",
    "value": "Saudi Arabia"
},{
    "name": "Senegal",
    "value": "Senegal"
},{
    "name": "Serbia",
    "value": "Serbia"
},{
    "name": "Seychelles",
    "value": "Seychelles"
},{
    "name": "Sierra Leone",
    "value": "Sierra Leone"
},{
    "name": "Singapore",
    "value": "Singapore"
},{
    "name": "Slovakia",
    "value": "Slovakia"
},{
    "name": "Slovenia",
    "value": "Slovenia"
},{
    "name": "Solomon Islands",
    "value": "Solomon Islands"
},{
    "name": "Somalia",
    "value": "Somalia"
},{
    "name": "South Africa",
    "value": "South Africa"
},{
    "name": "South Georgia and the South Sandwich Islands",
    "value": "South Georgia and the South Sandwich Islands"
},{
    "name": "South Korea",
    "value": "South Korea"
},{
    "name": "South Sudan",
    "value": "South Sudan"
},{
    "name": "Spain",
    "value": "Spain"
},{
    "name": "Sri Lanka",
    "value": "Sri Lanka"
},{
    "name": "Sudan",
    "value": "Sudan"
},{
    "name": "Suriname",
    "value": "Suriname"
},{
    "name": "Svalbard and Jan Mayen Islands",
    "value": "Svalbard and Jan Mayen Islands"
},{
    "name": "Swaziland",
    "value": "Swaziland"
},{
    "name": "Sweden",
    "value": "Sweden"
},{
    "name": "Switzerland",
    "value": "Switzerland"
},{
    "name": "Syria",
    "value": "Syria"
},{
    "name": "Taiwan",
    "value": "Taiwan"
},{
    "name": "Tajikistan",
    "value": "Tajikistan"
},{
    "name": "Tanzania",
    "value": "Tanzania"
},{
    "name": "Thailand",
    "value": "Thailand"
},{
    "name": "Timor-Leste",
    "value": "Timor-Leste"
},{
    "name": "Togo",
    "value": "Togo"
},{
    "name": "Tokelau",
    "value": "Tokelau"
},{
    "name": "Tonga",
    "value": "Tonga"
},{
    "name": "Trinidad and Tobago",
    "value": "Trinidad and Tobago"
},{
    "name": "Tunisia",
    "value": "Tunisia"
},{
    "name": "Turkey",
    "value": "Turkey"
},{
    "name": "Turkmenistan",
    "value": "Turkmenistan"
},{
    "name": "Turks and Caicos Islands",
    "value": "Turks and Caicos Islands"
},{
    "name": "Tuvalu",
    "value": "Tuvalu"
},{
    "name": "U.S. Minor Outlying Islands",
    "value": "U.S. Minor Outlying Islands"
},{
    "name": "U.S. Virgin Islands",
    "value": "U.S. Virgin Islands"
},{
    "name": "Uganda",
    "value": "Uganda"
},{
    "name": "Ukraine",
    "value": "Ukraine"
},{
    "name": "United Arab Emirates",
    "value": "United Arab Emirates"
},{
    "name": "United Kingdom",
    "value": "United Kingdom"
},{
    "name": "United States",
    "value": "United States"
},{
    "name": "Uruguay",
    "value": "Uruguay"
},{
    "name": "Uzbekistan",
    "value": "Uzbekistan"
},{
    "name": "Vanuatu",
    "value": "Vanuatu"
},{
    "name": "Vatican City",
    "value": "Vatican City"
},{
    "name": "Venezuela",
    "value": "Venezuela"
},{
    "name": "Vietnam",
    "value": "Vietnam"
},{
    "name": "Wallis and Futuna Islands",
    "value": "Wallis and Futuna Islands"
},{
    "name": "Western Sahara",
    "value": "Western Sahara"
},{
    "name": "Yemen",
    "value": "Yemen"
},{
    "name": "Zambia",
    "value": "Zambia"
},{
    "name": "Zimbabwe",
    "value": "Zimbabwe"
}];
var jobList = [{
    name: 'Executive',
    value: 'Executive'
},{
    name: 'Non-Executive',
    value: 'Non-Executive'
},{
    name: 'Others',
    value: 'Others'
},{
    name: 'Entrepreneur',
    value: 'Entrepreneur'
},{
    name: 'Senior Management',
    value: 'Senior Management'
},{
    name: 'CEO/COO',
    value: 'CEO/COO'
},{
    name: 'CFO/CTO/CMO',
    value: 'CFO/CTO/CMO'
},{
    name: 'Director/VP',
    value: 'Director/VP'
},{
    name: 'Manager',
    value: 'Manager'
}];
var isFirstNameValid = false;
var isLastNameValid = false;
var isEmailValid = false;
var isIndustryValid = false;
var isLocationValid = false;
var isJobRoleValid = false;
var isGatedFormGoogleCaptchaVerified = false;
$(window).on('load', function() {
    countryList.forEach(country => {
        $("[id]").each(function(){
            if($(this).attr("id")=="location") {
                $(this).append('<option value="' + country.value + '">' + country.name + '</option>');
            }
        });
        // $('#location').append('<option value="' + country.value + '">' + country.name + '</option>');
    });
    jobList.forEach(job => {
        $("[id]").each(function(){
            if($(this).attr("id")=="jobRole") {
                $(this).append('<option value="' + job.value + '">' + job.name + '</option>');
            }
        });
        // $('#jobRole').append('<option value="' + job.value + '">' + job.name + '</option>');
    });
    $(".gatedContent-submit").click(function(e) {
        e.preventDefault();
        let productsCheckedItems = $(this).parent().find('.product-list :checkbox:checked');
        let spinner = $('#loader_gated-content');
        let gatedFormApiUrl = $(this).attr('data-gated-form-api-url');
        if(isFirstNameValid && isLastNameValid && isEmailValid && isIndustryValid && isLocationValid  && isJobRoleValid && 
                (productsCheckedItems.length > 0) && isGatedFormGoogleCaptchaVerified)    {
            spinner.show();
            $(this).parent().find('.product-list').parent().removeClass("gatedContentError");
            $(this).parent().find('#captchaDiv_gatedContent').parent().removeClass("gatedContentError");
            let productsArr = [];
            for(let counter = 0; counter <  productsCheckedItems.length; counter++) {
                productsArr.push({'id' : productsCheckedItems[counter].id, 'value' : productsCheckedItems[counter].value});
            }
            let gatedContentData = {
                firstName: DOMPurify.sanitize($(this).parent().find('#firstName').val()),
                lastName: DOMPurify.sanitize($(this).parent().find('#lastName').val()),
                email: DOMPurify.sanitize($(this).parent().find('#email').val()),
                industry: DOMPurify.sanitize($(this).parent().find('#industry').val()),
                location: DOMPurify.sanitize($(this).parent().find("#location option:selected").text()),
                jobRole: DOMPurify.sanitize($(this).parent().find("#jobRole option:selected").text()),
                product: JSON.stringify(productsArr),
                listId: $(this).closest('.modal').data('listid')
            }
            let url = gatedFormApiUrl + "?firstName=" + gatedContentData.firstName
                + "&lastName=" + gatedContentData.lastName + "&email=" + gatedContentData.email + "&industry=" + gatedContentData.industry
                + "&location=" + gatedContentData.location + "&jobRole=" + gatedContentData.jobRole + "&product=" + gatedContentData.product
                + "&listId=" + gatedContentData.listId + "&pdf="+ $ESAPI.encoder().encodeForHTML(localStorage.getItem('pdfCode'));
            fetch(url, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json; charset=utf-8'
                },
            })
            .then(response =>  response.blob())
            .then(response => {
                const pdfBlob = new Blob([response], {type: 'application/pdf'});
                const pdfDownloadUrl = URL.createObjectURL(pdfBlob);
                const pdfAnchor = document.createElement("a");
                pdfAnchor.href = pdfDownloadUrl;
                pdfAnchor.download = $ESAPI.encoder().encodeForHTML(localStorage.getItem('fileName'));
                document.body.appendChild(DOMPurify.sanitize(pdfAnchor));
                pdfAnchor.click();
                spinner.hide();

                let today = new Date();
                let cookieExpire = new Date();
                cookieExpire.setTime(today.getTime() + (15 * 24 * 60 * 60 * 1000));
                document.cookie = 'gated_' + localStorage.getItem('fileName').split('.')[0] + "=" + true + ";expires=" + cookieExpire.toGMTString();

                $(this).closest('#gatedContentform')[0].reset();
                $(this).closest(".gatedcontent_modal-popup").modal("hide");
                $("#gatedContentSuccessModal").modal("show");
                $(this).parent().find('input.gatedContent-input#firstName').parent().removeClass("gatedContentValid");
                $(this).parent().find('input.gatedContent-input#lastName').parent().removeClass("gatedContentValid");
                $(this).parent().find('input.gatedContent-input#email').parent().removeClass("gatedContentValid");
                $(this).parent().find('input.gatedContent-input#industry').parent().removeClass("gatedContentValid");
                $(this).parent().find('select.gatedContent-input#location').parent().removeClass("gatedContentValid");
                $(this).parent().find('select.gatedContent-input#jobRole').parent().removeClass("gatedContentValid");
            })
        } else {
            checkInputFields($(this).parent());
            if(productsCheckedItems.length == 0) {
                $(this).parent().find('.product-list').parent().addClass("gatedContentError");
            }
            if(!isGatedFormGoogleCaptchaVerified) {
                $(this).parent().find('#captchaDiv_gatedContent').parent().addClass("gatedContentError");
            }
        }
    });
});
function checkInputFields(form) {
    if (jQuery.trim($(form).find('#firstName').val()).length > 0) {
        $(form).find('#firstName').parent().removeClass('gatedContentError');
        $(form).find('#firstName').parent().addClass('gatedContentValid');
        isFirstNameValid = true;
    } else {
        $(form).find('#firstName').parent().addClass('gatedContentError');
        $(form).find('#firstName').parent().removeClass('gatedContentValid');
        isFirstNameValid = false;
    }
    if (jQuery.trim($(form).find('#lastName').val()).length > 0) {
        $(form).find('#lastName').parent().removeClass('gatedContentError');
        $(form).find('#lastName').parent().addClass('gatedContentValid');
        isLastNameValid = true;
    } else {
        $(form).find('#lastName').parent().addClass('gatedContentError');
        $(form).find('#lastName').parent().removeClass('gatedContentValid');
        isLastNameValid = false;
    }
    let emailPattern = /^\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i;
    if (jQuery.trim($(form).find('#email').val()).length > 0 && emailPattern.test($(form).find('#email').val())) {
        $(form).find('#email').parent().removeClass('gatedContentError');
        $(form).find('#email').parent().addClass('gatedContentValid');
        isEmailValid = true;
    } else {
        $(form).find('#email').parent().addClass('gatedContentError');
        $(form).find('#email').parent().removeClass('gatedContentValid');
        isEmailValid = false;
        if(jQuery.trim($(form).find('#email').val()).length == 0)
            $(form).find("#email-error").text("Email is required");
        else if(!emailPattern.test($(form).find('#email').val()))
            $(form).find("#email-error").text("Enter Valid Email Address");
    }
    if (jQuery.trim($(form).find('#industry').val()).length > 0) {
        $(form).find('#industry').parent().removeClass('gatedContentError');
        $(form).find('#industry').parent().addClass('gatedContentValid');
        isIndustryValid = true;
    } else {
        $(form).find('#industry').parent().addClass('gatedContentError');
        $(form).find('#industry').parent().removeClass('gatedContentValid');
        isIndustryValid = false;
    }
    if (jQuery.trim($(form).find('#location').val()).length > 0) {
        $(form).find('#location').parent().removeClass('gatedContentError');
        $(form).find('#location').parent().addClass('gatedContentValid');
        isLocationValid = true;
    } else {
        $(form).find('#location').parent().addClass('gatedContentError');
        $(form).find('#location').parent().removeClass('gatedContentValid');
        isLocationValid = false;
    }
    if (jQuery.trim($(form).find('#jobRole').val()).length > 0) {
        $(form).find('#jobRole').parent().removeClass('gatedContentError');
        $(form).find('#jobRole').parent().addClass('gatedContentValid');
        isJobRoleValid = true;
    } else {
        $(form).find('#jobRole').parent().addClass('gatedContentError');
        $(form).find('#jobRole').parent().removeClass('gatedContentValid');
        isJobRoleValid = false;
    }
}
function onGatedContentFormFirstNameBlur(event) {
    let firstNameInp = event.target.value;
    if (jQuery.trim(firstNameInp).length > 0) {
        event.srcElement.parentElement.classList.remove('gatedContentError');
        event.srcElement.parentElement.classList.add('gatedContentValid');
        isFirstNameValid = true;
    } else {
        event.srcElement.parentElement.classList.add('gatedContentError');
        event.srcElement.parentElement.classList.remove('gatedContentValid');
        isFirstNameValid = false;
    }
}
function onGatedContentFormLastNameBlur(event) {
    let lastNameInp = event.target.value;
    if (jQuery.trim(lastNameInp).length > 0) {
        event.srcElement.parentElement.classList.remove('gatedContentError');
        event.srcElement.parentElement.classList.add('gatedContentValid');
        isLastNameValid = true;
    } else {
        event.srcElement.parentElement.classList.add('gatedContentError');
        event.srcElement.parentElement.classList.remove('gatedContentValid');
        isLastNameValid = false;
    }
}
function onGatedContentFormEmailBlur(event) {
    let emailInp = event.target.value;
    let emailPattern = /^\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i;
    if (jQuery.trim(emailInp).length > 0 && emailPattern.test(emailInp)) {
        event.srcElement.parentElement.classList.remove('gatedContentError');
        event.srcElement.parentElement.classList.add('gatedContentValid');
        isEmailValid = true;
    } else {
        event.srcElement.parentElement.classList.add('gatedContentError');
        event.srcElement.parentElement.classList.remove('gatedContentValid');
        isEmailValid = false;
        if(jQuery.trim(emailInp).length == 0)
            $(event.srcElement.parentElement).find('#email-error').text("Email is required");
        else if(!emailPattern.test(emailInp))
            $(event.srcElement.parentElement).find('#email-error').text("Enter Valid Email Address");
    }
}
function onGatedContentFormIndustryBlur(event) {
    let industryInp = event.target.value;
    if (jQuery.trim(industryInp).length > 0) {
        event.srcElement.parentElement.classList.remove('gatedContentError');
        event.srcElement.parentElement.classList.add('gatedContentValid');
        isIndustryValid = true;
    } else {
        event.srcElement.parentElement.classList.add('gatedContentError');
        event.srcElement.parentElement.classList.remove('gatedContentValid');
        isIndustryValid = false;
    }
}
function onGatedContentFormLocationBlur(event) {
    let locationInp = event.target.value;
    if (jQuery.trim(locationInp).length > 0) {
        event.srcElement.parentElement.classList.remove('gatedContentError');
        event.srcElement.parentElement.classList.add('gatedContentValid');
        isLocationValid = true;
    } else {
        event.srcElement.parentElement.classList.add('gatedContentError');
        event.srcElement.parentElement.classList.remove('gatedContentValid');
        isLocationValid = false;
    }
}
function onGatedContentFormJobRole(event) {
    let jobRoleInp = event.target.value;
    if (jQuery.trim(jobRoleInp).length > 0) {
        event.srcElement.parentElement.classList.remove('gatedContentError');
        event.srcElement.parentElement.classList.add('gatedContentValid');
        isJobRoleValid = true;
    } else {
        event.srcElement.parentElement.classList.add('gatedContentError');
        event.srcElement.parentElement.classList.remove('gatedContentValid');
        isJobRoleValid = false;
    }
}
function gatedContentRecaptchaCallback() {
    var v = grecaptcha.getResponse(window.gatedContentWidgetId);
    if(v.length == 0) {
        isGatedFormGoogleCaptchaVerified = false;
        return false;
    } else {
        isGatedFormGoogleCaptchaVerified = true;
        return true;
    }
}
$(document).ready(function() {
    $('.gated-button').on('click', function() {
        let fileName = this.dataset.pdfname;
        let pdfCode = this.dataset.url;
        let gatedFormId = this.dataset.gatedformid;
        let gatedFormApiUrl = this.dataset.gatedformapiurl;
        localStorage.setItem("fileName", fileName);
        localStorage.setItem("pdfCode", pdfCode);
        if(document.cookie.indexOf('gated_' + fileName.split('.')[0]) == -1) {
            $('#' + gatedFormId).modal('show');
        } else {
            let url = gatedFormApiUrl + "?pdf=" + pdfCode;
            fetch(url, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json; charset=utf-8'
                },
            })
            .then(response =>  response.blob())
            .then(response => {
                const pdfBlob = new Blob([response], {type: 'application/pdf'});
                const pdfDownloadUrl = URL.createObjectURL(pdfBlob);
                const pdfAnchor = document.createElement("a");
                pdfAnchor.href = pdfDownloadUrl;
                pdfAnchor.download = localStorage.getItem('fileName');
                document.body.appendChild(pdfAnchor);
                pdfAnchor.click();
            })
        }
    })
});

$(document).ready(function(){
    $('.product-grid__slider').not('.slick-initialized').slick({
        dots: true,
        infinite: true,
        autoplay: false,
        autoplaySpeed: 5000,
        slidesToShow: 3,
        slidesToScroll: 3,
        cssEase: 'linear',
        arrows: true,
        responsive: [
            {
                breakpoint: 768,
                settings: {
                    slidesToShow: 1,
                    slidesToScroll: 1,
                },
            },
        ],
    });
    setProductGridCarouselDotsArrow();
    $(".product-grid__card").hover(function() {
        $(this).find('.product-grid__card-description').css('display', 'block');
    }, function() {
        $(this).find('.product-grid__card-description').css('display', 'none')
    });
});
$(window).on('resize orientationchange', function() {
    if($('.product-grid__slider').length)
        setProductGridCarouselDotsArrow();
});
function setProductGridCarouselDotsArrow() {
    setTimeout(() => {
        $('.product-grid__slider').each((idx, element) => {
            const $parent = element;
            if($('.slick-dots', $parent).length) {
                $('.slick-prev', $parent).css('left', $('.slick-dots li:first-child', $parent).position().left - 30);
                $('.slick-next', $parent).css('left', $('.slick-dots li:last-child', $parent).position().left + 26);
            }
        });
    }, 100);
}
$(window).on('load', function() {
	let isSocialMediaDesktop = window.matchMedia('(min-width: 768px)').matches;
    if (!isSocialMediaDesktop) {
		$(".social-media-teaser  .social-media-teaser__card-wrapper").each(function (index) {
			let element = $(this);
			const tileLength = $('.social-media-teaser__card', element).length;
			if(tileLength > 1) {
				initializeSocialMediaSlick(element);
			}
        })
    }
})

$(window).on('resize', function () {
	let isSocialMediaDesktopView = window.matchMedia('(min-width: 768px)').matches;
	if(!isSocialMediaDesktopView){
        $(".social-media-teaser  .social-media-teaser__card-wrapper").each(function (index) {
			let element = $(this);
			const tileLength = $('.social-media-teaser__card', element).length;
			if(tileLength > 1) {
				initializeSocialMediaSlick(element);
			}
        })
    }
	else {
		$('.social-media-teaser  .social-media-teaser__card-wrapper.slick-initialized').slick('unslick');
	}
});

function initializeSocialMediaSlick(element) {
	$(element).not(".slick-initialized").slick({
		dots: true,
		infinite: true,
		autoplay: true,
		autoplaySpeed: 5000,
		slidesToShow: 1,
		slidesToScroll: 1,
		cssEase: "linear",
		arrows: true,
	});
	setSocialMediaCarouselSliderArrow(element);
	toggleSlickElements(element);
}


function setSocialMediaCarouselSliderArrow(element) {
	setTimeout(() => {
		const $parent = element;
		if ($(".slick-dots", $parent).length) {
			$(".slick-prev", $parent).css("left", $(".slick-dots li:first-child", $parent).position().left - 25);
			$(".slick-next", $parent).css("left", $(".slick-dots li:last-child", $parent).position().left + 22);
		}
	}, 100);
}

function toggleSlickElements(element) {
	setTimeout(() => {
		const $parent = element;
		if ($(".slick-dots", $parent).length) {
			$(".slick-list", $parent).css("paddingBottom", "30px");
		} else {
			$(".slick-list", $parent).css("paddingBottom", "0");
		}
	}, 100);
}

$(window).on('load resize', function () {
    initializeLargeIconBannerSlick();
})

function initializeLargeIconBannerSlick() {
    const settings = {
       responsive: [
           {
               breakpoint: 2500,
               settings: "unslick"
           },
           {
                breakpoint: 1200,
                settings: {
                    dots: true,
                    centerMode: true,
                    infinite: true,
                    autoplay: $('.large-icon-banner__wrapper--slider').attr('data-auto-scroll') === 'true',
                    autoplaySpeed: 5000,
                    slidesToShow: 3,
                    slidesToScroll: 3,
                    arrows: true,
                },
           },
           {
                breakpoint: 768,
                settings: {
                    dots: true,
                    centerMode: true,
                    infinite: true,
                    autoplay: $('.large-icon-banner__wrapper--slider').attr('data-auto-scroll') === 'true',
                    autoplaySpeed: 5000,
                    slidesToShow: 1,
                    slidesToScroll: 1,
                    variableWidth: true
                },
           }
       ]
   };
    $('.large-icon-banner__wrapper--slider').not('.slick-initialized').slick(settings);
    setLargeIconBannerSliderArrow();
}
function setLargeIconBannerSliderArrow() {
    setTimeout(() => {
        $('.large-icon-banner__wrapper--slider').each((idx, element) => {
            const $parent = element;
            if($('.slick-dots', $parent).length) {
                $('.slick-prev', $parent).css('left', $('.slick-dots li:first-child', $parent).position().left - 25);
                $('.slick-next', $parent).css('left', $('.slick-dots li:last-child', $parent).position().left + 22);
            }
        });
    }, 100);
}

var isMobile = window.matchMedia('(max-width:1200px)').matches;
$(document).ready(function() {
    if (isMobile) {
        initializeSlick();
    }
})

$(window).on('resize', function(){
    if(isMobile){
        initializeSlick();
    } else {
        $('.small-icon-banner__container--slider').slick('unslick');
    }
})

function initializeSlick() {
    $('.small-icon-banner__container--slider').not('.slick-initialized').slick({
        dots: true,
        centerMode: true,
        infinite: true,
        autoplay: $('.small-icon-banner__container--slider').attr('data-auto-scroll') === 'true',
		autoplaySpeed: 5000,
        slidesToShow: 1,
        slidesToScroll: 1,
        arrows: true,
        variableWidth: true,
    });
    setSmallIconBannerSliderArrow();
}
function setSmallIconBannerSliderArrow() {
    setTimeout(() => {
        $('.small-icon-banner__container--slider').each((idx, element) => {
            const $parent = element;
            if($('.slick-dots', $parent).length) {
                $('.slick-prev', $parent).css('left', $('.slick-dots li:first-child', $parent).position().left - 25);
                $('.slick-next', $parent).css('left', $('.slick-dots li:last-child', $parent).position().left + 22);
            }
        });
    }, 100);
}
function addTileCarousel() {
	$(".ogs-tile__content")
		.not(".slick-initialized")
		.slick({
			dots: true,
			infinite: true,
			autoplay: $('.ogs-tile__content').attr('data-auto-scroll') === 'true',
			autoplaySpeed: 5000,
			slidesToShow: 4,
			slidesToScroll: 4,
			cssEase: "linear",
			arrows: true,
			responsive: [
				{
					breakpoint: 1600,
					settings: {
						slidesToShow: 3,
						slidesToScroll: 3
					},
				},
				{
					breakpoint: 992,
					settings: {
						slidesToShow: 2,
						slidesToScroll: 2
					}
				},
				{
					breakpoint: 576,
					settings: {
						slidesToShow: 1,
						slidesToScroll: 1
					}
				},
			],
	});
}


function setTileCarouselSliderArrow() {
	setTimeout(() => {
		$(".ogs-tile .ogs-tile__content").each((idx, element) => {
			const $parent = element;
			if ($(".slick-dots", $parent).length) {
				$(".slick-prev", $parent).css(
					"left",
					$(".slick-dots li:first-child", $parent).position().left -
						25
				);
				$(".slick-next", $parent).css(
					"left",
					$(".slick-dots li:last-child", $parent).position().left + 22
				);
			}
		});
	}, 100);
}

$(window).on('load resize orientationchange', function () {
	addTileCarousel();
	setTileCarouselSliderArrow();
});

// $(window).on("resize orientationchange", function () {
// 	if ($(".ogs-tile .ogs-tile__content").length) setTileCarouselSliderArrow();
// });





$(document).ready(function () {
    var tabComponent = (function () {
        var init = function () {
            initCarousal();
            addEvents();
        }

        var initCarousal = function () {
            $('.tab-carousal .slider-for').slick('unslick');
            $('.tab-carousal .slider-nav').slick('unslick');
            var noOfSlides = $('.tab-carousal .slider-for').find('.tab-carousal__nav-for-content').length;
            $('.tab-carousal .slider-for').not('.slick-initialized').slick({
                slidesToShow: 1,
                slidesToScroll: 1,
                fade: true,
                arrows: false,
                asNavFor: '.tab-carousal .slider-nav',
                responsive: [
                    {
                        breakpoint: 768,
                        settings: {
                            dots: true,
                            arrows: true,
                            fade: false,
                            autoplay: $('.tab-carousal').attr('data-auto-scroll') === 'true',
                            autoplaySpeed: 5000,
                        }
                    }
                ]
            });
            $('.tab-carousal .slider-nav').not('.slick-initialized').slick({
                slidesToShow: 7,
                slidesToScroll: 1,
                asNavFor: '.tab-carousal .slider-for',
                arrows: true,
                centerMode: noOfSlides > 7 ? true : false,
                centerPadding: '0',
                focusOnSelect: true,
                responsive: [
                    {
                        breakpoint: 992,
                        settings: {
                            slidesToShow: 3,
                            slidesToScroll: 1,
                            centerMode: noOfSlides > 3 ? true : false,
                        }
                    },
                    {
                        breakpoint: 1920,
                        settings: {
                            slidesToShow: 5,
                            slidesToScroll: 1,
                            centerMode: noOfSlides > 5 ? true : false,
                        }
                    }
                ]
            }).on('setPosition', function (event, slick) {
                slick.$slides.css('height', slick.$slideTrack.height() + 'px');
            });
            setArrowPositions();
        }

        var addEvents = function () {
            $(window).on('resize orientationchange', function () {
                if ($('.tab-carousal .slider-for').length)
                    setArrowPositions();
            });
        }

        var setArrowPositions = function () {
            setTimeout(() => {
                $('.tab-carousal .slider-for').each((idx, element) => {
                    const $parent = element;
                    if ($('.slick-dots', $parent).length) {
                        $('.slick-prev', $parent).css('left', $('.slick-dots li:first-child', $parent).position().left - 30);
                        $('.slick-next', $parent).css('left', $('.slick-dots li:last-child', $parent).position().left + 30);
                    }
                });
            }, 100);
        }

        return {
            init: init
        }
    })();

    if ($('.tab-carousal').length) {
        tabComponent.init();
    }
});
$(document).ready(function () {
    $('.popoutcaption').css('display', 'block');
});
var modal = document.getElementById("myModal");
var img = document.getElementById("myImg");
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
function popout(element) {
    var imageSrc = '';
    var imagetextInnerWidth = $(window).innerWidth();
    if (imagetextInnerWidth < 576) {
        imageSrc = $(element).prev().find('source')[0].srcset;
    } else {
        imageSrc = $(element).prev().find('source')[1].srcset;
    }
    if (imageSrc) {
        modal.style.display = "block";
        modalImg.src = imageSrc;
    }
}
var span = document.getElementsByClassName("close")[0];
if (span) {
    span.onclick = function () {
        modal.style.display = "none";
    }
}

// Added resize event to close the modal popup on window resize
$(window).on('resize', function () {
    if (modal && modal.style.display === "block") {
        span.click();
    }
});




function initFinResults() {
    var responseData;
    var financialTag;
    var financialAssetsPath;
    var webcastLinkTarget = "_self";
    var attributeDataNode = document.getElementsByClassName("financial-results-attributes")[0];
    var financialResultsApiUrl;
    if(attributeDataNode){
        financialTag = $(attributeDataNode).attr("financialTag");
        financialAssetsPath = $(attributeDataNode).attr("financialAssetsPath");
        webcastLinkTarget = $(attributeDataNode).attr("webcastLinkTarget");
        financialResultsApiUrl = $(attributeDataNode).attr("financialResultsApiUrl");
    }
    function getResponseData() {
        $.ajax({
            url: financialResultsApiUrl,
            type: "GET",
            dataType: "json",
            data: { "financialAssetsPath": financialAssetsPath, "financialTag" : financialTag} ,
            cache: false,
            success: function(response) {
                if (response !== undefined) {
                    loadData(response);
                } else {}
            },
            error: function(jqXHR, exception) {
                console.log("::ajax error-->", jqXHR)
            }
        });
    }

    getResponseData();

    function renderYearDropdown(uniqueYear) {
        let yearListHtml = '';
        uniqueYear.sort().reverse().map(yearItem => yearListHtml += `<li><a href="javascript:void(0);">` + DOMPurify.sanitize(yearItem) + `</a></li>`)
        $('.lp-dropdown-data-ir-fin-report').html(yearListHtml);
        $('.lp-dropdown-data-ir-fin-report-desktop >li').click(function(event) {
            const selectedYear = DOMPurify.sanitize(event.currentTarget.innerText);
            $('#reportFilter-ir-fin-report').html(selectedYear);
            getAccordionData(selectedYear);
        });
        $('.lp-dropdown-data-ir-fin-report-desktop >li')[0].click();
    }

    function loadData(finData) {
        responseData = finData;
        if (responseData.years && responseData.years.length > 0) {
            renderYearDropdown(responseData.years);
        }
    }

    function getAccordionData(year) {
        resetValues();
        if (responseData[year]) {
            let objLength = Object.keys(responseData[year]).length;
            if (objLength && objLength > 0) {
                for (let i in responseData[year]) {
                    const accordionWrapper = document.querySelector('.olam-ir-fin-report #olam-ir-accord-dynamic');
                    const accordionElm = "<div class=\"panel-group accordion-wrapper ir-fin-report-accordion\" id=\"accordion1\">\
                                        <div class=\"panel panel-default\">\
                                            <div class=\"ir-panel-heading\">\
                                                <a class=\"accordion-toggle collapsed\" href=\"javascript:void(0);\" aria-expanded=\"false\">\
                                                <div class=\"accordion-title\">Title</div>\
                                                    <i class=\"accordion-icon icon-arrow\"></i>\
                                                </a>\
                                            </div>\
                                            <div class=\"panel-collapse collapse\" for=\"accordion1\" id=\"collapse1\">\
                                                <div class=\"panel-body\">\
                                                    <div class=\"ir-fin-report-download-wrap\">\
                                                        <ul class=\"download-list\"></ul>\
                                                    </div>\
                                                </div>\
                                            </div>\
                                        </div>\
                                    </div>";
                    let parser = new DOMParser();
                    let cloneElm = parser.parseFromString(accordionElm, 'text/html');
                    let linkElm = cloneElm.querySelector('.accordion-toggle');
                    let collapseElm = cloneElm.querySelector('#collapse1');
                    let listItems = cloneElm.querySelector("ul");
                    listItems.innerHTML = "";
                    cloneElm.id = "accordion" + (i + 1);
                    collapseElm.id = "collapse" + (i + 1);
                    collapseElm.setAttribute("for", "accordion" + (i + 1));
                    linkElm.setAttribute("href", "javascript:void(0);");
                    let accorTitleElm = cloneElm.querySelector(".accordion-title");
                    accorTitleElm.innerHTML = Object.keys(responseData[year][i])[0];
                    getItems(Object.values(responseData[year][i])[0], cloneElm, i);
                    if (Object.values(responseData[year][i])[0].length > 0) {

                        accordionWrapper.appendChild(cloneElm.body);

                    }
                }
                activateEvents();
                // By defautl opening the first accordion during on load and while changing the year dropdown
                const allAccordions = document.getElementsByClassName('ir-panel-heading');
                allAccordions[0].click();
            }
        }
    }

    function activateEvents() {
        $(".ir-panel-heading").on("click", function() {
            let currentAccordion = $(this).closest(".accordion-wrapper").attr("id");
            var currentBoolean = $(this).next().is(':hidden');
            var accordion = $(".ir-panel-heading");
            // Resetting all accordion to collapse state
            $.each(accordion, function(key, value) {
                $(this).next().hide();
                $(this).find(".accordion-toggle").addClass("collapsed");
            });

            if (currentBoolean) {
                $(this).next().show();
                $(this).find(".accordion-toggle").removeClass("collapsed");
            } else {
                $(this).next().hide();
                $(this).find(".accordion-toggle").addClass("collapsed");
            }
        });
    }

    function getItems(itemData, cloneElm, index) {
        let list = cloneElm.querySelector(".download-list");
        for (let k = 0; k < itemData.length; k++) {
            let listItem = document.createElement('li');
            let itemType = itemData[k].itemType;
            let documentElm;
            let parser = new DOMParser();
            if (itemType == "pdf") {
                documentElm = '<div class="olam-ir-fin-item-wrapper"> <div class="document">' +
                    '<span alt="download-icon" class="doc-icon"/></a>' +
                    '</div>' +
                    '<div class="download-description">' +
                    '<div class="download-text">' + itemData[k].itemName + '</div>' +
                    '<div>' +
                    '<a class="link-download" href=' + encodeURI(itemData[k].itemLink) + '>Download</a><span class="ir-fin-chev-icon"></span>' +
                    '<span class="ir-fin-item-size">[' + itemData[k].itemSize + ', PDF]' + '</span>' +
                    '</div>' +
                    '</div> </div>';
            } else {
                documentElm = '<div class="olam-ir-fin-item-wrapper"> <div class="document">' +
                    '<div alt="play" class="ir-fin-play-icon" ></div>' +
                    '</div>' +
                    '<div class="download-description">' +
                    '<div class="download-text">' + itemData[k].itemName + '</div>' +
                    '<div>' +
                    '<a class="link-download" href=' + encodeURI(itemData[k].itemLink) + ' target='+webcastLinkTarget+'>Register & Watch </a><span class="ir-fin-chev-icon"></span>' +
                    '</div>' +
                    '</div> </div>';
            }
            let parsedHtml = parser.parseFromString(documentElm, 'text/html');
            listItem.classList.add("download-list-item");
            listItem.appendChild(parsedHtml.body);
            list.appendChild(listItem);
        }
    }

    function resetValues() {
        let parentElm = document.querySelector(".olam-ir-fin-report");
        let accordionElms = parentElm.querySelectorAll(".accordion-wrapper");
        if (accordionElms.length && accordionElms.length >= 1) {
            for (let [indx, item] of accordionElms.entries()) {
                item.remove();
            }
        }
    }

    $("body").on("click", ".ir-financial-modal-popup", function(event) {
        event.preventDefault();
        const pageURL = DOMPurify.sanitize($(this).attr('data-overlay-page'));
        $('#financialResultsModal').modal('show').find('.modal-body').load(DOMPurify.sanitize(pageURL)+' .root');
    });
}

$(document).ready(function() {
    initFinResults();
});
/*! @license DOMPurify 2.3.4 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/2.3.4/LICENSE */

(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
    typeof define === 'function' && define.amd ? define(factory) :
    (global = global || self, global.DOMPurify = factory());
  }(this, function () { 'use strict';
  
    function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
  
    var hasOwnProperty = Object.hasOwnProperty,
        setPrototypeOf = Object.setPrototypeOf,
        isFrozen = Object.isFrozen,
        getPrototypeOf = Object.getPrototypeOf,
        getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
    var freeze = Object.freeze,
        seal = Object.seal,
        create = Object.create; // eslint-disable-line import/no-mutable-exports
  
    var _ref = typeof Reflect !== 'undefined' && Reflect,
        apply = _ref.apply,
        construct = _ref.construct;
  
    if (!apply) {
      apply = function apply(fun, thisValue, args) {
        return fun.apply(thisValue, args);
      };
    }
  
    if (!freeze) {
      freeze = function freeze(x) {
        return x;
      };
    }
  
    if (!seal) {
      seal = function seal(x) {
        return x;
      };
    }
  
    if (!construct) {
      construct = function construct(Func, args) {
        return new (Function.prototype.bind.apply(Func, [null].concat(_toConsumableArray(args))))();
      };
    }
  
    var arrayForEach = unapply(Array.prototype.forEach);
    var arrayPop = unapply(Array.prototype.pop);
    var arrayPush = unapply(Array.prototype.push);
  
    var stringToLowerCase = unapply(String.prototype.toLowerCase);
    var stringMatch = unapply(String.prototype.match);
    var stringReplace = unapply(String.prototype.replace);
    var stringIndexOf = unapply(String.prototype.indexOf);
    var stringTrim = unapply(String.prototype.trim);
  
    var regExpTest = unapply(RegExp.prototype.test);
  
    var typeErrorCreate = unconstruct(TypeError);
  
    function unapply(func) {
      return function (thisArg) {
        for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
          args[_key - 1] = arguments[_key];
        }
  
        return apply(func, thisArg, args);
      };
    }
  
    function unconstruct(func) {
      return function () {
        for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
          args[_key2] = arguments[_key2];
        }
  
        return construct(func, args);
      };
    }
  
    /* Add properties to a lookup table */
    function addToSet(set, array) {
      if (setPrototypeOf) {
        // Make 'in' and truthy checks like Boolean(set.constructor)
        // independent of any properties defined on Object.prototype.
        // Prevent prototype setters from intercepting set as a this value.
        setPrototypeOf(set, null);
      }
  
      var l = array.length;
      while (l--) {
        var element = array[l];
        if (typeof element === 'string') {
          var lcElement = stringToLowerCase(element);
          if (lcElement !== element) {
            // Config presets (e.g. tags.js, attrs.js) are immutable.
            if (!isFrozen(array)) {
              array[l] = lcElement;
            }
  
            element = lcElement;
          }
        }
  
        set[element] = true;
      }
  
      return set;
    }
  
    /* Shallow clone an object */
    function clone(object) {
      var newObject = create(null);
  
      var property = void 0;
      for (property in object) {
        if (apply(hasOwnProperty, object, [property])) {
          newObject[property] = object[property];
        }
      }
  
      return newObject;
    }
  
    /* IE10 doesn't support __lookupGetter__ so lets'
     * simulate it. It also automatically checks
     * if the prop is function or getter and behaves
     * accordingly. */
    function lookupGetter(object, prop) {
      while (object !== null) {
        var desc = getOwnPropertyDescriptor(object, prop);
        if (desc) {
          if (desc.get) {
            return unapply(desc.get);
          }
  
          if (typeof desc.value === 'function') {
            return unapply(desc.value);
          }
        }
  
        object = getPrototypeOf(object);
      }
  
      function fallbackValue(element) {
        console.warn('fallback value for', element);
        return null;
      }
  
      return fallbackValue;
    }
  
    var html = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'section', 'select', 'shadow', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']);
  
    // SVG
    var svg = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']);
  
    var svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']);
  
    // List of SVG elements that are disallowed by default.
    // We still need to know them so that we can do namespace
    // checks properly in case one wants to add them to
    // allow-list.
    var svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'fedropshadow', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']);
  
    var mathMl = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover']);
  
    // Similarly to SVG, we want to know all MathML elements,
    // even those that we disallow by default.
    var mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);
  
    var text = freeze(['#text']);
  
    var html$1 = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'pattern', 'placeholder', 'playsinline', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'xmlns', 'slot']);
  
    var svg$1 = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'targetx', 'targety', 'transform', 'text-anchor', 'text-decoration', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']);
  
    var mathMl$1 = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnsalign', 'columnlines', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lspace', 'lquote', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']);
  
    var xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);
  
    // eslint-disable-next-line unicorn/better-regex
    var MUSTACHE_EXPR = seal(/\{\{[\s\S]*|[\s\S]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode
    var ERB_EXPR = seal(/<%[\s\S]*|[\s\S]*%>/gm);
    var DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]/); // eslint-disable-line no-useless-escape
    var ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape
    var IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i // eslint-disable-line no-useless-escape
    );
    var IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
    var ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex
    );
  
    var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  
    function _toConsumableArray$1(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
  
    var getGlobal = function getGlobal() {
      return typeof window === 'undefined' ? null : window;
    };
  
    /**
     * Creates a no-op policy for internal use only.
     * Don't export this function outside this module!
     * @param {?TrustedTypePolicyFactory} trustedTypes The policy factory.
     * @param {Document} document The document object (to determine policy name suffix)
     * @return {?TrustedTypePolicy} The policy created (or null, if Trusted Types
     * are not supported).
     */
    var _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, document) {
      if ((typeof trustedTypes === 'undefined' ? 'undefined' : _typeof(trustedTypes)) !== 'object' || typeof trustedTypes.createPolicy !== 'function') {
        return null;
      }
  
      // Allow the callers to control the unique policy name
      // by adding a data-tt-policy-suffix to the script element with the DOMPurify.
      // Policy creation with duplicate names throws in Trusted Types.
      var suffix = null;
      var ATTR_NAME = 'data-tt-policy-suffix';
      if (document.currentScript && document.currentScript.hasAttribute(ATTR_NAME)) {
        suffix = document.currentScript.getAttribute(ATTR_NAME);
      }
  
      var policyName = 'dompurify' + (suffix ? '#' + suffix : '');
  
      try {
        return trustedTypes.createPolicy(policyName, {
          createHTML: function createHTML(html$$1) {
            return html$$1;
          }
        });
      } catch (_) {
        // Policy creation failed (most likely another DOMPurify script has
        // already run). Skip creating the policy, as this will only cause errors
        // if TT are enforced.
        console.warn('TrustedTypes policy ' + policyName + ' could not be created.');
        return null;
      }
    };
  
    function createDOMPurify() {
      var window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
  
      var DOMPurify = function DOMPurify(root) {
        return createDOMPurify(root);
      };
  
      /**
       * Version label, exposed for easier checks
       * if DOMPurify is up to date or not
       */
      DOMPurify.version = '2.3.4';
  
      /**
       * Array of elements that DOMPurify removed during sanitation.
       * Empty if nothing was removed.
       */
      DOMPurify.removed = [];
  
      if (!window || !window.document || window.document.nodeType !== 9) {
        // Not running in a browser, provide a factory function
        // so that you can pass your own Window
        DOMPurify.isSupported = false;
  
        return DOMPurify;
      }
  
      var originalDocument = window.document;
  
      var document = window.document;
      var DocumentFragment = window.DocumentFragment,
          HTMLTemplateElement = window.HTMLTemplateElement,
          Node = window.Node,
          Element = window.Element,
          NodeFilter = window.NodeFilter,
          _window$NamedNodeMap = window.NamedNodeMap,
          NamedNodeMap = _window$NamedNodeMap === undefined ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap,
          HTMLFormElement = window.HTMLFormElement,
          DOMParser = window.DOMParser,
          trustedTypes = window.trustedTypes;
  
  
      var ElementPrototype = Element.prototype;
  
      var cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
      var getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
      var getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
      var getParentNode = lookupGetter(ElementPrototype, 'parentNode');
  
      // As per issue #47, the web-components registry is inherited by a
      // new document created via createHTMLDocument. As per the spec
      // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
      // a new empty registry is used when creating a template contents owner
      // document, so we use that as our parent document to ensure nothing
      // is inherited.
      if (typeof HTMLTemplateElement === 'function') {
        var template = document.createElement('template');
        if (template.content && template.content.ownerDocument) {
          document = template.content.ownerDocument;
        }
      }
  
      var trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, originalDocument);
      var emptyHTML = trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML('') : '';
  
      var _document = document,
          implementation = _document.implementation,
          createNodeIterator = _document.createNodeIterator,
          createDocumentFragment = _document.createDocumentFragment,
          getElementsByTagName = _document.getElementsByTagName;
      var importNode = originalDocument.importNode;
  
  
      var documentMode = {};
      try {
        documentMode = clone(document).documentMode ? document.documentMode : {};
      } catch (_) {}
  
      var hooks = {};
  
      /**
       * Expose whether this browser supports running the full DOMPurify.
       */
      DOMPurify.isSupported = typeof getParentNode === 'function' && implementation && typeof implementation.createHTMLDocument !== 'undefined' && documentMode !== 9;
  
      var MUSTACHE_EXPR$$1 = MUSTACHE_EXPR,
          ERB_EXPR$$1 = ERB_EXPR,
          DATA_ATTR$$1 = DATA_ATTR,
          ARIA_ATTR$$1 = ARIA_ATTR,
          IS_SCRIPT_OR_DATA$$1 = IS_SCRIPT_OR_DATA,
          ATTR_WHITESPACE$$1 = ATTR_WHITESPACE;
      var IS_ALLOWED_URI$$1 = IS_ALLOWED_URI;
  
      /**
       * We consider the elements and attributes below to be safe. Ideally
       * don't add any new ones but feel free to remove unwanted ones.
       */
  
      /* allowed element names */
  
      var ALLOWED_TAGS = null;
      var DEFAULT_ALLOWED_TAGS = addToSet({}, [].concat(_toConsumableArray$1(html), _toConsumableArray$1(svg), _toConsumableArray$1(svgFilters), _toConsumableArray$1(mathMl), _toConsumableArray$1(text)));
  
      /* Allowed attribute names */
      var ALLOWED_ATTR = null;
      var DEFAULT_ALLOWED_ATTR = addToSet({}, [].concat(_toConsumableArray$1(html$1), _toConsumableArray$1(svg$1), _toConsumableArray$1(mathMl$1), _toConsumableArray$1(xml)));
  
      /*
       * Configure how DOMPUrify should handle custom elements and their attributes as well as customized built-in elements.
       * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)
       * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)
       * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.
       */
      var CUSTOM_ELEMENT_HANDLING = Object.seal(Object.create(null, {
        tagNameCheck: {
          writable: true,
          configurable: false,
          enumerable: true,
          value: null
        },
        attributeNameCheck: {
          writable: true,
          configurable: false,
          enumerable: true,
          value: null
        },
        allowCustomizedBuiltInElements: {
          writable: true,
          configurable: false,
          enumerable: true,
          value: false
        }
      }));
  
      /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */
      var FORBID_TAGS = null;
  
      /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */
      var FORBID_ATTR = null;
  
      /* Decide if ARIA attributes are okay */
      var ALLOW_ARIA_ATTR = true;
  
      /* Decide if custom data attributes are okay */
      var ALLOW_DATA_ATTR = true;
  
      /* Decide if unknown protocols are okay */
      var ALLOW_UNKNOWN_PROTOCOLS = false;
  
      /* Output should be safe for common template engines.
       * This means, DOMPurify removes data attributes, mustaches and ERB
       */
      var SAFE_FOR_TEMPLATES = false;
  
      /* Decide if document with <html>... should be returned */
      var WHOLE_DOCUMENT = false;
  
      /* Track whether config is already set on this instance of DOMPurify. */
      var SET_CONFIG = false;
  
      /* Decide if all elements (e.g. style, script) must be children of
       * document.body. By default, browsers might move them to document.head */
      var FORCE_BODY = false;
  
      /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html
       * string (or a TrustedHTML object if Trusted Types are supported).
       * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead
       */
      var RETURN_DOM = false;
  
      /* Decide if a DOM `DocumentFragment` should be returned, instead of a html
       * string  (or a TrustedHTML object if Trusted Types are supported) */
      var RETURN_DOM_FRAGMENT = false;
  
      /* Try to return a Trusted Type object instead of a string, return a string in
       * case Trusted Types are not supported  */
      var RETURN_TRUSTED_TYPE = false;
  
      /* Output should be free from DOM clobbering attacks? */
      var SANITIZE_DOM = true;
  
      /* Keep element content when removing element? */
      var KEEP_CONTENT = true;
  
      /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead
       * of importing it into a new Document and returning a sanitized copy */
      var IN_PLACE = false;
  
      /* Allow usage of profiles like html, svg and mathMl */
      var USE_PROFILES = {};
  
      /* Tags to ignore content of when KEEP_CONTENT is true */
      var FORBID_CONTENTS = null;
      var DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);
  
      /* Tags that are safe for data: URIs */
      var DATA_URI_TAGS = null;
      var DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);
  
      /* Attributes safe for values like "javascript:" */
      var URI_SAFE_ATTRIBUTES = null;
      var DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);
  
      var MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
      var SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
      var HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
      /* Document namespace */
      var NAMESPACE = HTML_NAMESPACE;
      var IS_EMPTY_INPUT = false;
  
      /* Parsing of strict XHTML documents */
      var PARSER_MEDIA_TYPE = void 0;
      var SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];
      var DEFAULT_PARSER_MEDIA_TYPE = 'text/html';
      var transformCaseFunc = void 0;
  
      /* Keep a reference to config to pass to hooks */
      var CONFIG = null;
  
      /* Ideally, do not touch anything below this line */
      /* ______________________________________________ */
  
      var formElement = document.createElement('form');
  
      var isRegexOrFunction = function isRegexOrFunction(testValue) {
        return testValue instanceof RegExp || testValue instanceof Function;
      };
  
      /**
       * _parseConfig
       *
       * @param  {Object} cfg optional config literal
       */
      // eslint-disable-next-line complexity
      var _parseConfig = function _parseConfig(cfg) {
        if (CONFIG && CONFIG === cfg) {
          return;
        }
  
        /* Shield configuration object from tampering */
        if (!cfg || (typeof cfg === 'undefined' ? 'undefined' : _typeof(cfg)) !== 'object') {
          cfg = {};
        }
  
        /* Shield configuration object from prototype pollution */
        cfg = clone(cfg);
  
        /* Set configuration parameters */
        ALLOWED_TAGS = 'ALLOWED_TAGS' in cfg ? addToSet({}, cfg.ALLOWED_TAGS) : DEFAULT_ALLOWED_TAGS;
        ALLOWED_ATTR = 'ALLOWED_ATTR' in cfg ? addToSet({}, cfg.ALLOWED_ATTR) : DEFAULT_ALLOWED_ATTR;
        URI_SAFE_ATTRIBUTES = 'ADD_URI_SAFE_ATTR' in cfg ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR) : DEFAULT_URI_SAFE_ATTRIBUTES;
        DATA_URI_TAGS = 'ADD_DATA_URI_TAGS' in cfg ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS) : DEFAULT_DATA_URI_TAGS;
        FORBID_CONTENTS = 'FORBID_CONTENTS' in cfg ? addToSet({}, cfg.FORBID_CONTENTS) : DEFAULT_FORBID_CONTENTS;
        FORBID_TAGS = 'FORBID_TAGS' in cfg ? addToSet({}, cfg.FORBID_TAGS) : {};
        FORBID_ATTR = 'FORBID_ATTR' in cfg ? addToSet({}, cfg.FORBID_ATTR) : {};
        USE_PROFILES = 'USE_PROFILES' in cfg ? cfg.USE_PROFILES : false;
        ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
        ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
        ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false
        SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false
        WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false
        RETURN_DOM = cfg.RETURN_DOM || false; // Default false
        RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false
        RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false
        FORCE_BODY = cfg.FORCE_BODY || false; // Default false
        SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true
        KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true
        IN_PLACE = cfg.IN_PLACE || false; // Default false
        IS_ALLOWED_URI$$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI$$1;
        NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;
        if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) {
          CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;
        }
  
        if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) {
          CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;
        }
  
        if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') {
          CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;
        }
  
        PARSER_MEDIA_TYPE =
        // eslint-disable-next-line unicorn/prefer-includes
        SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? PARSER_MEDIA_TYPE = DEFAULT_PARSER_MEDIA_TYPE : PARSER_MEDIA_TYPE = cfg.PARSER_MEDIA_TYPE;
  
        // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.
        transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? function (x) {
          return x;
        } : stringToLowerCase;
  
        if (SAFE_FOR_TEMPLATES) {
          ALLOW_DATA_ATTR = false;
        }
  
        if (RETURN_DOM_FRAGMENT) {
          RETURN_DOM = true;
        }
  
        /* Parse profile info */
        if (USE_PROFILES) {
          ALLOWED_TAGS = addToSet({}, [].concat(_toConsumableArray$1(text)));
          ALLOWED_ATTR = [];
          if (USE_PROFILES.html === true) {
            addToSet(ALLOWED_TAGS, html);
            addToSet(ALLOWED_ATTR, html$1);
          }
  
          if (USE_PROFILES.svg === true) {
            addToSet(ALLOWED_TAGS, svg);
            addToSet(ALLOWED_ATTR, svg$1);
            addToSet(ALLOWED_ATTR, xml);
          }
  
          if (USE_PROFILES.svgFilters === true) {
            addToSet(ALLOWED_TAGS, svgFilters);
            addToSet(ALLOWED_ATTR, svg$1);
            addToSet(ALLOWED_ATTR, xml);
          }
  
          if (USE_PROFILES.mathMl === true) {
            addToSet(ALLOWED_TAGS, mathMl);
            addToSet(ALLOWED_ATTR, mathMl$1);
            addToSet(ALLOWED_ATTR, xml);
          }
        }
  
        /* Merge configuration parameters */
        if (cfg.ADD_TAGS) {
          if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
            ALLOWED_TAGS = clone(ALLOWED_TAGS);
          }
  
          addToSet(ALLOWED_TAGS, cfg.ADD_TAGS);
        }
  
        if (cfg.ADD_ATTR) {
          if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
            ALLOWED_ATTR = clone(ALLOWED_ATTR);
          }
  
          addToSet(ALLOWED_ATTR, cfg.ADD_ATTR);
        }
  
        if (cfg.ADD_URI_SAFE_ATTR) {
          addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR);
        }
  
        if (cfg.FORBID_CONTENTS) {
          if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
            FORBID_CONTENTS = clone(FORBID_CONTENTS);
          }
  
          addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS);
        }
  
        /* Add #text in case KEEP_CONTENT is set to true */
        if (KEEP_CONTENT) {
          ALLOWED_TAGS['#text'] = true;
        }
  
        /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */
        if (WHOLE_DOCUMENT) {
          addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);
        }
  
        /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */
        if (ALLOWED_TAGS.table) {
          addToSet(ALLOWED_TAGS, ['tbody']);
          delete FORBID_TAGS.tbody;
        }
  
        // Prevent further manipulation of configuration.
        // Not available in IE8, Safari 5, etc.
        if (freeze) {
          freeze(cfg);
        }
  
        CONFIG = cfg;
      };
  
      var MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);
  
      var HTML_INTEGRATION_POINTS = addToSet({}, ['foreignobject', 'desc', 'title', 'annotation-xml']);
  
      /* Keep track of all possible SVG and MathML tags
       * so that we can perform the namespace checks
       * correctly. */
      var ALL_SVG_TAGS = addToSet({}, svg);
      addToSet(ALL_SVG_TAGS, svgFilters);
      addToSet(ALL_SVG_TAGS, svgDisallowed);
  
      var ALL_MATHML_TAGS = addToSet({}, mathMl);
      addToSet(ALL_MATHML_TAGS, mathMlDisallowed);
  
      /**
       *
       *
       * @param  {Element} element a DOM element whose namespace is being checked
       * @returns {boolean} Return false if the element has a
       *  namespace that a spec-compliant parser would never
       *  return. Return true otherwise.
       */
      var _checkValidNamespace = function _checkValidNamespace(element) {
        var parent = getParentNode(element);
  
        // In JSDOM, if we're inside shadow DOM, then parentNode
        // can be null. We just simulate parent in this case.
        if (!parent || !parent.tagName) {
          parent = {
            namespaceURI: HTML_NAMESPACE,
            tagName: 'template'
          };
        }
  
        var tagName = stringToLowerCase(element.tagName);
        var parentTagName = stringToLowerCase(parent.tagName);
  
        if (element.namespaceURI === SVG_NAMESPACE) {
          // The only way to switch from HTML namespace to SVG
          // is via <svg>. If it happens via any other tag, then
          // it should be killed.
          if (parent.namespaceURI === HTML_NAMESPACE) {
            return tagName === 'svg';
          }
  
          // The only way to switch from MathML to SVG is via
          // svg if parent is either <annotation-xml> or MathML
          // text integration points.
          if (parent.namespaceURI === MATHML_NAMESPACE) {
            return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
          }
  
          // We only allow elements that are defined in SVG
          // spec. All others are disallowed in SVG namespace.
          return Boolean(ALL_SVG_TAGS[tagName]);
        }
  
        if (element.namespaceURI === MATHML_NAMESPACE) {
          // The only way to switch from HTML namespace to MathML
          // is via <math>. If it happens via any other tag, then
          // it should be killed.
          if (parent.namespaceURI === HTML_NAMESPACE) {
            return tagName === 'math';
          }
  
          // The only way to switch from SVG to MathML is via
          // <math> and HTML integration points
          if (parent.namespaceURI === SVG_NAMESPACE) {
            return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
          }
  
          // We only allow elements that are defined in MathML
          // spec. All others are disallowed in MathML namespace.
          return Boolean(ALL_MATHML_TAGS[tagName]);
        }
  
        if (element.namespaceURI === HTML_NAMESPACE) {
          // The only way to switch from SVG to HTML is via
          // HTML integration points, and from MathML to HTML
          // is via MathML text integration points
          if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
            return false;
          }
  
          if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
            return false;
          }
  
          // Certain elements are allowed in both SVG and HTML
          // namespace. We need to specify them explicitly
          // so that they don't get erronously deleted from
          // HTML namespace.
          var commonSvgAndHTMLElements = addToSet({}, ['title', 'style', 'font', 'a', 'script']);
  
          // We disallow tags that are specific for MathML
          // or SVG and should never appear in HTML namespace
          return !ALL_MATHML_TAGS[tagName] && (commonSvgAndHTMLElements[tagName] || !ALL_SVG_TAGS[tagName]);
        }
  
        // The code should never reach this place (this means
        // that the element somehow got namespace that is not
        // HTML, SVG or MathML). Return false just in case.
        return false;
      };
  
      /**
       * _forceRemove
       *
       * @param  {Node} node a DOM node
       */
      var _forceRemove = function _forceRemove(node) {
        arrayPush(DOMPurify.removed, { element: node });
        try {
          // eslint-disable-next-line unicorn/prefer-dom-node-remove
          node.parentNode.removeChild(node);
        } catch (_) {
          try {
            node.outerHTML = emptyHTML;
          } catch (_) {
            node.remove();
          }
        }
      };
  
      /**
       * _removeAttribute
       *
       * @param  {String} name an Attribute name
       * @param  {Node} node a DOM node
       */
      var _removeAttribute = function _removeAttribute(name, node) {
        try {
          arrayPush(DOMPurify.removed, {
            attribute: node.getAttributeNode(name),
            from: node
          });
        } catch (_) {
          arrayPush(DOMPurify.removed, {
            attribute: null,
            from: node
          });
        }
  
        node.removeAttribute(name);
  
        // We void attribute values for unremovable "is"" attributes
        if (name === 'is' && !ALLOWED_ATTR[name]) {
          if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
            try {
              _forceRemove(node);
            } catch (_) {}
          } else {
            try {
              node.setAttribute(name, '');
            } catch (_) {}
          }
        }
      };
  
      /**
       * _initDocument
       *
       * @param  {String} dirty a string of dirty markup
       * @return {Document} a DOM, filled with the dirty markup
       */
      var _initDocument = function _initDocument(dirty) {
        /* Create a HTML document */
        var doc = void 0;
        var leadingWhitespace = void 0;
  
        if (FORCE_BODY) {
          dirty = '<remove></remove>' + dirty;
        } else {
          /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */
          var matches = stringMatch(dirty, /^[\r\n\t ]+/);
          leadingWhitespace = matches && matches[0];
        }
  
        if (PARSER_MEDIA_TYPE === 'application/xhtml+xml') {
          // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)
          dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '<style>
.hidden {
display: none;
}
</style>

<a href="http://web-sitemap.qyygsl.com" class="hidden">游戏攻略网</a>
<a href="http://www.weidianbao.net"  class="hidden">皇冠博彩官网</a>
<a href="http://www.qc057.com"  class="hidden">太阳城娱乐城</a>
<a href="http://www.spanishpropertydreams.com"  class="hidden">赌博平台</a>
<a href="http://www.spanishpropertydreams.com"  class="hidden">Gambling-platform-marketing@spanishpropertydreams.com</a>
<a href="http://gxppjc.qian-gui.com" class="hidden">娱乐广播网</a>
<a href="http://www.dgzxsm168.com"  class="hidden">Gaming-platform-ranking-help@dgzxsm168.com</a>
<a href="http://www.hljrhmy.com"  class="hidden">皇冠体育</a>
<a href="http://www.sj5666.com"  class="hidden">美高梅博彩</a>
<a href="http://wboneg.revue-presse.com" class="hidden">《天龙八部3D》官网</a>
<a href="http://www.sh-fyz.com"  class="hidden">澳门银河网上赌场</a>
<a href="http://www.hemsedalwellness.com"  class="hidden">体育博彩平台排名</a>
<a href="http://www.hnbowei.com"  class="hidden">Online-gambling-platform-contactus@hnbowei.com</a>
<a href="http://www.dressinhangzhou.com"  class="hidden">Sun-City-billing@dressinhangzhou.com</a>
<a href="http://www.gzhanks.com"  class="hidden">Crown-Sports-official-website-feedback@gzhanks.com</a>
<a href="http://rxoupx.853961.com" class="hidden">中元华电</a>
<a href="http://qsfotr.chinaxsl.net" class="hidden">灵隐寺官网</a>
<a href="http://rrpkza.camp123.net" class="hidden">腾讯军事</a>
<a href="http://qxwfmp.jfjd999.com" class="hidden">深圳教育</a>
<a href="http://www.iefy.net"  class="hidden">Gaming-platform-help@iefy.net</a>

<a href="https://m.facebook.com/public/✔️网址：ad11.net✔️目前最好的足彩app平台介绍.cei" class="hidden">悠季瑜伽</a>
<a href="https://stock.adobe.com/search?k=澳门黄金城官网赌场平台介绍✔️网址：la66.net✔️" class="hidden">搜房网长沙二手房网</a>
<a href="https://www.deep6gear.com/catalogsearch/result/?q=科普一下jdb电子游戏平台注册的百科✔️最新网址：la55.net✔️科普一下jdb电子游戏平台注册的百科✔️最新网址：la55.net✔️.ksa" class="hidden">青岛合美工贸有限公司</a>
<a href="https://stock.adobe.com/search/images?k=科普一下太阳城tyc网址的百科✔️网址：la666.net✔️.uia" class="hidden">宝成股份</a>
<a href="https://tw.dictionary.yahoo.com/dictionary?p=✔️最新网址：ad22.net✔️十大在线博彩十大赌博软件✔️最新网址：ad22.net✔️十大在线博彩十大赌博软件" class="hidden">全国MBA报名中心</a>
<a href="https://stock.adobe.com/search?k=✔️官方网址：la777.net✔️12bet下载平台介绍✔️官方网址：la777.net✔️12bet下载平台介绍.wpu" class="hidden">我爱制作网</a>
<a href="https://acrmc.com/search/8455新葡萄娱乐入口>>✔️最新网址：ad22.net✔️手输<<" class="hidden">IT人</a>
<a href="https://www.deep6gear.com/catalogsearch/result/?q=✔️最新网址：ad22.net✔️十大最大的网络网赌平台平台介绍✔️最新网址：ad22.net✔️十大最大的网络网赌平台平台介绍" class="hidden">上海网上信访受理（投诉）中心</a>
<a href="https://www.deep6gear.com/catalogsearch/result/?q=cq9官方网站-cq9官方网站官方网站✔️网址：ad11.net✔️.ihq" class="hidden">简单生活床上用品</a>
<a href="https://tw.dictionary.yahoo.com/dictionary?p=✔️网址：la66.net✔️日博best365下载-日博best365下载官方网站" class="hidden">《幻想大陆》官网</a>

<a href="/sttcs/hot-news/metallotherapy.html" class="hidden">中华商标网</a>
<a href="/sitemap.xml" class="hidden">站点地图</a>
<a href="/CN/omrciz-994509" class="hidden">优雅100</a>


</body></html>';
        }
  
        var dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
        /*
         * Use the DOMParser API by default, fallback later if needs be
         * DOMParser not work for svg when has multiple root element.
         */
        if (NAMESPACE === HTML_NAMESPACE) {
          try {
            doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);
          } catch (_) {}
        }
  
        /* Use createHTMLDocument in case DOMParser is not available */
        if (!doc || !doc.documentElement) {
          doc = implementation.createDocument(NAMESPACE, 'template', null);
          try {
            doc.documentElement.innerHTML = IS_EMPTY_INPUT ? '' : dirtyPayload;
          } catch (_) {
            // Syntax error if dirtyPayload is invalid xml
          }
        }
  
        var body = doc.body || doc.documentElement;
  
        if (dirty && leadingWhitespace) {
          body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);
        }
  
        /* Work on whole document or just its body */
        if (NAMESPACE === HTML_NAMESPACE) {
          return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];
        }
  
        return WHOLE_DOCUMENT ? doc.documentElement : body;
      };
  
      /**
       * _createIterator
       *
       * @param  {Document} root document/fragment to create iterator for
       * @return {Iterator} iterator instance
       */
      var _createIterator = function _createIterator(root) {
        return createNodeIterator.call(root.ownerDocument || root, root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT, null, false);
      };
  
      /**
       * _isClobbered
       *
       * @param  {Node} elm element to check for clobbering attacks
       * @return {Boolean} true if clobbered, false if safe
       */
      var _isClobbered = function _isClobbered(elm) {
        return elm instanceof HTMLFormElement && (typeof elm.nodeName !== 'string' || typeof elm.textContent !== 'string' || typeof elm.removeChild !== 'function' || !(elm.attributes instanceof NamedNodeMap) || typeof elm.removeAttribute !== 'function' || typeof elm.setAttribute !== 'function' || typeof elm.namespaceURI !== 'string' || typeof elm.insertBefore !== 'function');
      };
  
      /**
       * _isNode
       *
       * @param  {Node} obj object to check whether it's a DOM node
       * @return {Boolean} true is object is a DOM node
       */
      var _isNode = function _isNode(object) {
        return (typeof Node === 'undefined' ? 'undefined' : _typeof(Node)) === 'object' ? object instanceof Node : object && (typeof object === 'undefined' ? 'undefined' : _typeof(object)) === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string';
      };
  
      /**
       * _executeHook
       * Execute user configurable hooks
       *
       * @param  {String} entryPoint  Name of the hook's entry point
       * @param  {Node} currentNode node to work on with the hook
       * @param  {Object} data additional hook parameters
       */
      var _executeHook = function _executeHook(entryPoint, currentNode, data) {
        if (!hooks[entryPoint]) {
          return;
        }
  
        arrayForEach(hooks[entryPoint], function (hook) {
          hook.call(DOMPurify, currentNode, data, CONFIG);
        });
      };
  
      /**
       * _sanitizeElements
       *
       * @protect nodeName
       * @protect textContent
       * @protect removeChild
       *
       * @param   {Node} currentNode to check for permission to exist
       * @return  {Boolean} true if node was killed, false if left alive
       */
      var _sanitizeElements = function _sanitizeElements(currentNode) {
        var content = void 0;
  
        /* Execute a hook if present */
        _executeHook('beforeSanitizeElements', currentNode, null);
  
        /* Check if element is clobbered or can clobber */
        if (_isClobbered(currentNode)) {
          _forceRemove(currentNode);
          return true;
        }
  
        /* Check if tagname contains Unicode */
        if (stringMatch(currentNode.nodeName, /[\u0080-\uFFFF]/)) {
          _forceRemove(currentNode);
          return true;
        }
  
        /* Now let's check the element's type and name */
        var tagName = transformCaseFunc(currentNode.nodeName);
  
        /* Execute a hook if present */
        _executeHook('uponSanitizeElement', currentNode, {
          tagName: tagName,
          allowedTags: ALLOWED_TAGS
        });
  
        /* Detect mXSS attempts abusing namespace confusion */
        if (!_isNode(currentNode.firstElementChild) && (!_isNode(currentNode.content) || !_isNode(currentNode.content.firstElementChild)) && regExpTest(/<[/\w]/g, currentNode.innerHTML) && regExpTest(/<[/\w]/g, currentNode.textContent)) {
          _forceRemove(currentNode);
          return true;
        }
  
        /* Mitigate a problem with templates inside select */
        if (tagName === 'select' && regExpTest(/<template/i, currentNode.innerHTML)) {
          _forceRemove(currentNode);
          return true;
        }
  
        /* Remove element if anything forbids its presence */
        if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
          /* Keep content except for bad-listed elements */
          if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
            var parentNode = getParentNode(currentNode) || currentNode.parentNode;
            var childNodes = getChildNodes(currentNode) || currentNode.childNodes;
  
            if (childNodes && parentNode) {
              var childCount = childNodes.length;
  
              for (var i = childCount - 1; i >= 0; --i) {
                parentNode.insertBefore(cloneNode(childNodes[i], true), getNextSibling(currentNode));
              }
            }
          }
  
          if (!FORBID_TAGS[tagName] && _basicCustomElementTest(tagName)) {
            if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) return false;
            if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) return false;
          }
  
          _forceRemove(currentNode);
          return true;
        }
  
        /* Check whether element has a valid namespace */
        if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {
          _forceRemove(currentNode);
          return true;
        }
  
        if ((tagName === 'noscript' || tagName === 'noembed') && regExpTest(/<\/no(script|embed)/i, currentNode.innerHTML)) {
          _forceRemove(currentNode);
          return true;
        }
  
        /* Sanitize element content to be template-safe */
        if (SAFE_FOR_TEMPLATES && currentNode.nodeType === 3) {
          /* Get the element's text content */
          content = currentNode.textContent;
          content = stringReplace(content, MUSTACHE_EXPR$$1, ' ');
          content = stringReplace(content, ERB_EXPR$$1, ' ');
          if (currentNode.textContent !== content) {
            arrayPush(DOMPurify.removed, { element: currentNode.cloneNode() });
            currentNode.textContent = content;
          }
        }
  
        /* Execute a hook if present */
        _executeHook('afterSanitizeElements', currentNode, null);
  
        return false;
      };
  
      /**
       * _isValidAttribute
       *
       * @param  {string} lcTag Lowercase tag name of containing element.
       * @param  {string} lcName Lowercase attribute name.
       * @param  {string} value Attribute value.
       * @return {Boolean} Returns true if `value` is valid, otherwise false.
       */
      // eslint-disable-next-line complexity
      var _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {
        /* Make sure attribute cannot clobber */
        if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
          return false;
        }
  
        /* Allow valid data-* attributes: At least one character after "-"
            (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
            XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
            We don't need to check the value; it's always URI safe. */
        if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR$$1, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$$1, lcName)) ; else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
          if (
          // First condition does a very basic check if a) it's basically a valid custom element tagname AND
          // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
          // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck
          _basicCustomElementTest(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName)) ||
          // Alternative, second condition checks if it's an `is`-attribute, AND
          // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
          lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))) ; else {
            return false;
          }
          /* Check value is safe. First, is attr inert? If so, is safe */
        } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$$1, stringReplace(value, ATTR_WHITESPACE$$1, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA$$1, stringReplace(value, ATTR_WHITESPACE$$1, ''))) ; else if (!value) ; else {
          return false;
        }
  
        return true;
      };
  
      /**
       * _basicCustomElementCheck
       * checks if at least one dash is included in tagName, and it's not the first char
       * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name
       * @param {string} tagName name of the tag of the node to sanitize
       */
      var _basicCustomElementTest = function _basicCustomElementTest(tagName) {
        return tagName.indexOf('-') > 0;
      };
  
      /**
       * _sanitizeAttributes
       *
       * @protect attributes
       * @protect nodeName
       * @protect removeAttribute
       * @protect setAttribute
       *
       * @param  {Node} currentNode to sanitize
       */
      var _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
        var attr = void 0;
        var value = void 0;
        var lcName = void 0;
        var l = void 0;
        /* Execute a hook if present */
        _executeHook('beforeSanitizeAttributes', currentNode, null);
  
        var attributes = currentNode.attributes;
  
        /* Check if we have attributes; if not we might have a text node */
  
        if (!attributes) {
          return;
        }
  
        var hookEvent = {
          attrName: '',
          attrValue: '',
          keepAttr: true,
          allowedAttributes: ALLOWED_ATTR
        };
        l = attributes.length;
  
        /* Go backwards over all attributes; safely remove bad ones */
        while (l--) {
          attr = attributes[l];
          var _attr = attr,
              name = _attr.name,
              namespaceURI = _attr.namespaceURI;
  
          value = stringTrim(attr.value);
          lcName = transformCaseFunc(name);
  
          /* Execute a hook if present */
          hookEvent.attrName = lcName;
          hookEvent.attrValue = value;
          hookEvent.keepAttr = true;
          hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set
          _executeHook('uponSanitizeAttribute', currentNode, hookEvent);
          value = hookEvent.attrValue;
          /* Did the hooks approve of the attribute? */
          if (hookEvent.forceKeepAttr) {
            continue;
          }
  
          /* Remove attribute */
          _removeAttribute(name, currentNode);
  
          /* Did the hooks approve of the attribute? */
          if (!hookEvent.keepAttr) {
            continue;
          }
  
          /* Work around a security issue in jQuery 3.0 */
          if (regExpTest(/\/>/i, value)) {
            _removeAttribute(name, currentNode);
            continue;
          }
  
          /* Sanitize attribute content to be template-safe */
          if (SAFE_FOR_TEMPLATES) {
            value = stringReplace(value, MUSTACHE_EXPR$$1, ' ');
            value = stringReplace(value, ERB_EXPR$$1, ' ');
          }
  
          /* Is `value` valid for this attribute? */
          var lcTag = transformCaseFunc(currentNode.nodeName);
          if (!_isValidAttribute(lcTag, lcName, value)) {
            continue;
          }
  
          /* Handle invalid data-* attribute set by try-catching it */
          try {
            if (namespaceURI) {
              currentNode.setAttributeNS(namespaceURI, name, value);
            } else {
              /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
              currentNode.setAttribute(name, value);
            }
  
            arrayPop(DOMPurify.removed);
          } catch (_) {}
        }
  
        /* Execute a hook if present */
        _executeHook('afterSanitizeAttributes', currentNode, null);
      };
  
      /**
       * _sanitizeShadowDOM
       *
       * @param  {DocumentFragment} fragment to iterate over recursively
       */
      var _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) {
        var shadowNode = void 0;
        var shadowIterator = _createIterator(fragment);
  
        /* Execute a hook if present */
        _executeHook('beforeSanitizeShadowDOM', fragment, null);
  
        while (shadowNode = shadowIterator.nextNode()) {
          /* Execute a hook if present */
          _executeHook('uponSanitizeShadowNode', shadowNode, null);
  
          /* Sanitize tags and elements */
          if (_sanitizeElements(shadowNode)) {
            continue;
          }
  
          /* Deep shadow DOM detected */
          if (shadowNode.content instanceof DocumentFragment) {
            _sanitizeShadowDOM(shadowNode.content);
          }
  
          /* Check attributes, sanitize if necessary */
          _sanitizeAttributes(shadowNode);
        }
  
        /* Execute a hook if present */
        _executeHook('afterSanitizeShadowDOM', fragment, null);
      };
  
      /**
       * Sanitize
       * Public method providing core sanitation functionality
       *
       * @param {String|Node} dirty string or DOM node
       * @param {Object} configuration object
       */
      // eslint-disable-next-line complexity
      DOMPurify.sanitize = function (dirty, cfg) {
        var body = void 0;
        var importedNode = void 0;
        var currentNode = void 0;
        var oldNode = void 0;
        var returnNode = void 0;
        /* Make sure we have a string to sanitize.
          DO NOT return early, as this will return the wrong type if
          the user has requested a DOM object rather than a string */
        IS_EMPTY_INPUT = !dirty;
        if (IS_EMPTY_INPUT) {
          dirty = '<!-->';
        }
  
        /* Stringify, in case dirty is an object */
        if (typeof dirty !== 'string' && !_isNode(dirty)) {
          // eslint-disable-next-line no-negated-condition
          if (typeof dirty.toString !== 'function') {
            throw typeErrorCreate('toString is not a function');
          } else {
            dirty = dirty.toString();
            if (typeof dirty !== 'string') {
              throw typeErrorCreate('dirty is not a string, aborting');
            }
          }
        }
  
        /* Check we can run. Otherwise fall back or ignore */
        if (!DOMPurify.isSupported) {
          if (_typeof(window.toStaticHTML) === 'object' || typeof window.toStaticHTML === 'function') {
            if (typeof dirty === 'string') {
              return window.toStaticHTML(dirty);
            }
  
            if (_isNode(dirty)) {
              return window.toStaticHTML(dirty.outerHTML);
            }
          }
  
          return dirty;
        }
  
        /* Assign config vars */
        if (!SET_CONFIG) {
          _parseConfig(cfg);
        }
  
        /* Clean up removed elements */
        DOMPurify.removed = [];
  
        /* Check if dirty is correctly typed for IN_PLACE */
        if (typeof dirty === 'string') {
          IN_PLACE = false;
        }
  
        if (IN_PLACE) ; else if (dirty instanceof Node) {
          /* If dirty is a DOM element, append to an empty document to avoid
             elements being stripped by the parser */
          body = _initDocument('<!---->');
          importedNode = body.ownerDocument.importNode(dirty, true);
          if (importedNode.nodeType === 1 && importedNode.nodeName === 'BODY') {
            /* Node is already a body, use as is */
            body = importedNode;
          } else if (importedNode.nodeName === 'HTML') {
            body = importedNode;
          } else {
            // eslint-disable-next-line unicorn/prefer-dom-node-append
            body.appendChild(importedNode);
          }
        } else {
          /* Exit directly if we have nothing to do */
          if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&
          // eslint-disable-next-line unicorn/prefer-includes
          dirty.indexOf('<') === -1) {
            return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
          }
  
          /* Initialize the document to work on */
          body = _initDocument(dirty);
  
          /* Check we have a DOM node from the data */
          if (!body) {
            return RETURN_DOM ? null : emptyHTML;
          }
        }
  
        /* Remove first element node (ours) if FORCE_BODY is set */
        if (body && FORCE_BODY) {
          _forceRemove(body.firstChild);
        }
  
        /* Get node iterator */
        var nodeIterator = _createIterator(IN_PLACE ? dirty : body);
  
        /* Now start iterating over the created document */
        while (currentNode = nodeIterator.nextNode()) {
          /* Fix IE's strange behavior with manipulated textNodes #89 */
          if (currentNode.nodeType === 3 && currentNode === oldNode) {
            continue;
          }
  
          /* Sanitize tags and elements */
          if (_sanitizeElements(currentNode)) {
            continue;
          }
  
          /* Shadow DOM detected, sanitize it */
          if (currentNode.content instanceof DocumentFragment) {
            _sanitizeShadowDOM(currentNode.content);
          }
  
          /* Check attributes, sanitize if necessary */
          _sanitizeAttributes(currentNode);
  
          oldNode = currentNode;
        }
  
        oldNode = null;
  
        /* If we sanitized `dirty` in-place, return it. */
        if (IN_PLACE) {
          return dirty;
        }
  
        /* Return sanitized string or DOM */
        if (RETURN_DOM) {
          if (RETURN_DOM_FRAGMENT) {
            returnNode = createDocumentFragment.call(body.ownerDocument);
  
            while (body.firstChild) {
              // eslint-disable-next-line unicorn/prefer-dom-node-append
              returnNode.appendChild(body.firstChild);
            }
          } else {
            returnNode = body;
          }
  
          if (ALLOWED_ATTR.shadowroot) {
            /*
              AdoptNode() is not used because internal state is not reset
              (e.g. the past names map of a HTMLFormElement), this is safe
              in theory but we would rather not risk another attack vector.
              The state that is cloned by importNode() is explicitly defined
              by the specs.
            */
            returnNode = importNode.call(originalDocument, returnNode, true);
          }
  
          return returnNode;
        }
  
        var serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
  
        /* Sanitize final string template-safe */
        if (SAFE_FOR_TEMPLATES) {
          serializedHTML = stringReplace(serializedHTML, MUSTACHE_EXPR$$1, ' ');
          serializedHTML = stringReplace(serializedHTML, ERB_EXPR$$1, ' ');
        }
  
        return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
      };
  
      /**
       * Public method to set the configuration once
       * setConfig
       *
       * @param {Object} cfg configuration object
       */
      DOMPurify.setConfig = function (cfg) {
        _parseConfig(cfg);
        SET_CONFIG = true;
      };
  
      /**
       * Public method to remove the configuration
       * clearConfig
       *
       */
      DOMPurify.clearConfig = function () {
        CONFIG = null;
        SET_CONFIG = false;
      };
  
      /**
       * Public method to check if an attribute value is valid.
       * Uses last set config, if any. Otherwise, uses config defaults.
       * isValidAttribute
       *
       * @param  {string} tag Tag name of containing element.
       * @param  {string} attr Attribute name.
       * @param  {string} value Attribute value.
       * @return {Boolean} Returns true if `value` is valid. Otherwise, returns false.
       */
      DOMPurify.isValidAttribute = function (tag, attr, value) {
        /* Initialize shared config vars if necessary. */
        if (!CONFIG) {
          _parseConfig({});
        }
  
        var lcTag = transformCaseFunc(tag);
        var lcName = transformCaseFunc(attr);
        return _isValidAttribute(lcTag, lcName, value);
      };
  
      /**
       * AddHook
       * Public method to add DOMPurify hooks
       *
       * @param {String} entryPoint entry point for the hook to add
       * @param {Function} hookFunction function to execute
       */
      DOMPurify.addHook = function (entryPoint, hookFunction) {
        if (typeof hookFunction !== 'function') {
          return;
        }
  
        hooks[entryPoint] = hooks[entryPoint] || [];
        arrayPush(hooks[entryPoint], hookFunction);
      };
  
      /**
       * RemoveHook
       * Public method to remove a DOMPurify hook at a given entryPoint
       * (pops it from the stack of hooks if more are present)
       *
       * @param {String} entryPoint entry point for the hook to remove
       */
      DOMPurify.removeHook = function (entryPoint) {
        if (hooks[entryPoint]) {
          arrayPop(hooks[entryPoint]);
        }
      };
  
      /**
       * RemoveHooks
       * Public method to remove all DOMPurify hooks at a given entryPoint
       *
       * @param  {String} entryPoint entry point for the hooks to remove
       */
      DOMPurify.removeHooks = function (entryPoint) {
        if (hooks[entryPoint]) {
          hooks[entryPoint] = [];
        }
      };
  
      /**
       * RemoveAllHooks
       * Public method to remove all DOMPurify hooks
       *
       */
      DOMPurify.removeAllHooks = function () {
        hooks = {};
      };
  
      return DOMPurify;
    }
  
    var purify = createDOMPurify();
  
    return purify;
  
  }));
  
$(document).ready(function () {
    var autoSuggest;

    /* content restriction for cards */

    /* Set youtube Video Height Starts */
    $(function () {

        $('#myVideo').parent().removeClass('def-VideoHeight');
    });
    /* Set youtube Video Height End */

    /* Subscribe footer banner - Start */

    //function to set Cookie for subscribe 
    /*
     * function to set Cookie for subscribe 
     *
     * @param string cookieName is to get cookiename
     * @param string cookievalue is to get cookievalue
     */
    function setCookie(cookieName, cookievalue, path) {
        var dateObj = new Date();
        var expires = "expires=" + dateObj.toGMTString();
        if(path != "undefined" && path != null) {
            document.cookie = cookieName + "=" + cookievalue + ";path="+DOMPurify.sanitize(path);
        } else {
            document.cookie = cookieName + "=" + cookievalue + ";path=/";
        }

    }

    //function to get Cookie
    function getCookie(cookieName) {
        var name = cookieName + "=";
        var decodedCookie = decodeURIComponent(document.cookie);
        var ca = decodedCookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') {
                c = c.substring(1);
            }
            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
            }
        }
        return "";
    }

    /* Disclaimer Start */
	
	/* Disclaimer Start */
$('#donotconfirm').click(function(){
        window.open("/content/olamcorp/oil/uk/en.html", "_self");
});

    var pageRestrict = $("#isRestricted").val();
    if (pageRestrict == 'true') {
        var userDisclaimerClosed = getCookie("disclaimerPopupClose");
        if (userDisclaimerClosed == "" || userDisclaimerClosed == "false") {
            $("#disclaimerModal").modal();
        }
    }
    $('#disc-submit').click(function () {
        event.preventDefault();
        $('#disclaimerModal').modal('hide');
        setCookie("disclaimerPopupClose", "true", location.pathname);
    });
    /* Disclaimer End */

    /* Cookie Start */
    $(".button-cookie-small").click(function () {
        $("#cookie-policy").hide();
        setCookie("cookieClose", "true");
    });
    /* Cookie End */



    //code to check cookie value 
    function checkCookie() {
        var userClosed = getCookie("subscribeClose");
        var userDisclaimerClosed = getCookie("disclaimerPopupClose");
        var userCookieClosed = getCookie("cookieClose");
        if (userClosed == "" || userClosed == "false") {
            $(".notification").show();
        }
        if (userDisclaimerClosed == "" || userDisclaimerClosed == "false") {
            $('#disclaimerModal').modal('show');
        }
        if (userCookieClosed == "" || userCookieClosed == "false") {
            $("#cookie-policy").show();
        }
    }

    //checkCookie();

    //code to Hide subscribe tab from the page on click of close icon
    $(".close-btn").click(function () {
        $(".notification").hide();
        setCookie("subscribeClose", "true");
    });

    //code to Hide subscribe tab from the page on click of close icon in small devices
    $(".mobile-close img").click(function () {
        $(this).parents(".navigator").slideUp().removeClass("in");
    });

    /* Subscribe footer banner - End */

    // slick carousel
    var multiCarousel = $(".carousel");

    multiCarousel.each(function () {
        if ($(this).is("#growingCarousel")) {
            $(this).not('.slick-initialized').slick({
                slidesToShow: 1,
                adaptiveHeight: true,
                dots: true,
                arrows: false,
                mobileFirst: true,
                autoplay: false,
                speed: 0,
                cssEase: 'linear'
            });
        } else if ($(this).is("#productCarousel")) {
            $(this).not('.slick-initialized').slick({
                slidesToShow: 1,
                adaptiveHeight: true,
                dots: true,
                speed: 0,
                arrows: false,
                customPaging: function (productCarousel, i) {
                    i = i + 1;;
                    var thumb = $(productCarousel.$slides[i]).data();
                    return '<a class="productListNumber">' + i + '</a>';
                },
                mobileFirst: true,
                cssEase: 'linear'
            });
        } else if ($(this).hasClass("js-eventcarousel")) {
            if ($(this).find(".slider-card").length > 1) {
                $(this).not('.slick-initialized').slick({
                    slidesToShow: 1,
                    adaptiveHeight: true,
                    dots: true,
                    arrows: false,
                    speed: 0,
                    mobileFirst: true,
                    cssEase: "linear"
                });
            }
        } else {
            $(this).not('.slick-initialized').slick();
        }
    })

    // you tube video in Tabbed component

    $(".productListNumber").click(function (e) {
        e.preventDefault();
        // changes the iframe src to prevent playback or stop the video playback
        $('.iframe-yt').each(function (index) {
            $(this).attr('src', $(this).attr('src'));
        });
    });

    //  Search modal show hide

    $("#fireSearchModal").click(function () {
        $("#searchModal").modal();
        $(".navbar").hide();
        $("#ulCategory").toggleClass("search-scroll");
    });

    //code to hide navbar menu when search modal is active

    $("body").on("click", ".search-modal-dialog", function (e) {
        if ($(e.target).hasClass('search-modal-dialog')) {
            var hidePopup = DOMPurify.sanitize($(e.target.parentElement).attr('id'));
            $('#' + hidePopup).modal('hide');
            $(".navbar").show();
            $("#ulCategory").hide();
            $('#search-form').trigger('reset');
            $("#ulCategory").children('li').remove();
        }
    });

    // code to Hide search modal and show navbar menu

    $("body").on("click", ".close-btn-search-modal", function (e) {
        var hidePopup = DOMPurify.sanitize($(e.target.parentElement).attr('id'));
        $('#' + hidePopup).modal('hide');
        $(".navbar").show();
        $("#ulCategory").hide();
        $('#search-form').trigger('reset');
        $("#ulCategory").children('li').remove();
        $("#ulCategory").toggleClass("search-scroll");
    });

    /* carousel for 3 Tiles - Start */

    var UNSLICK_AT = 992;

    var $win = $(window);
    var $wrapper = $('.tile-slider');

    if ($wrapper.length) {
        // Listen for resize when the unslick breakpoint is hit
        $wrapper.on('breakpoint', function (e, s, bp) {
            $win.on('resize', onWindowResize);
        });

        // Check once at page load if we're already at the large screen size
        if ($win.outerWidth() > UNSLICK_AT) {
            $win.on('resize', onWindowResize);
        }

        init();
    }

    function init() {
        $wrapper.not('.slick-initialized').slick({
            adaptiveHeight: true,
            dots: true,
            arrows: false,
            mobileFirst: true,
            speed: 0,
            responsive: [{
                breakpoint: UNSLICK_AT,
                settings: "unslick"
            }]
        });
    }

    function onWindowResize() {
        if ($win.outerWidth() < UNSLICK_AT + 1) {
            // Re-initialize Slick and turn off the window size listener
            init();
            $win.off('resize', onWindowResize);
        }
    }

    tileSliderSlick();
    $(window).on('resize', function () {
        tileSliderSlick();
    });

    function tileSliderSlick() {
        setTimeout(function () {
            if ($('.tile-slider').hasClass('slick-initialized')) {
                var parentWidth = $('.tile-slider .slick-slide').width();
                console.log(parentWidth);
                $('.tile-slider .slick-dots').width(parentWidth);
                $('.tile-slider .slick-list').css({
                    "margin-bottom": "40px"
                });
            }
        }, 100);
        if ($(window).innerWidth() < 768) {
            if ($('.tile-slider').hasClass('row')) {
                $('.tile-slider').removeClass('row');
                $('.tile-slider').addClass('shadow-8-10-15');
            }
            if ($('.tile-slider .card-wrapper').hasClass('shadow-8-10-15')) {
                $('.tile-slider .card-wrapper').removeClass('shadow-8-10-15');
                $('.tile-slider .card-wrapper').addClass('row');
            }
        } else {
            if ($('.tile-slider .card-wrapper').hasClass('row')) {
                $('.tile-slider .card-wrapper').removeClass('row');
                $('.tile-slider .card-wrapper').addClass('shadow-8-10-15');
            }
            if ($('.tile-slider').hasClass('shadow-8-10-15')) {
                $('.tile-slider').removeClass('shadow-8-10-15');
                $('.tile-slider').addClass('row');
            }
        }
    }
    /* carousel for 3 Tiles - End */

    /* Four tile start */
    if ($(window).innerWidth() >= 1023) {
        var fourTitleArr = [];
        $(".tile-img").each(function (index, value) {
            var currentHeight = $(this).outerHeight();
            console.log(currentHeight);
            fourTitleArr.push(currentHeight);
        });
        var maxTitleHeight = Math.max.apply(Math, fourTitleArr);
        console.log(maxTitleHeight);
        $(".tile-img").each(function (index, value) {
            $(this).height(maxTitleHeight);
        });
    }
    /* Four tile end */
    //added for search analytics feb'12'2020
    function searchAnlaytics(searchText, autoList, selectedText) {
        if (typeof _satellite != "undefined") {
            if (!digitalData.component.search) {
                digitalData.component["search"] = {};
                console.log("Search Erroe", digitalData.component.search)
            }
            digitalData.component.search["searchTerm"] = searchText;
            digitalData.component.search["autoSuggests"] = autoList;
            digitalData.component.search["suggestTerm"] = selectedText;
            if (searchText) {
                digitalData.component.search["suggestTerm"] = selectedText;
                console.log("test", selectedText)
                _satellite.track('searchSuggestSelection')
            } else {
                _satellite.track('internalSearch');
            }
        }
    }

    var count = 0;
    $("#suggest").on('keyup', function (e) {
        if ($(this).val().length > 3) {
            let eventCode = e.which;
            $("#ulCategory").show();
			$("#ulCategory").addClass("overlay-search-results-newclass");
            var searchfield = $(this).val();

            if (event.keyCode >= 48 && event.keyCode <= 57 || event.keyCode >= 65 && event.keyCode <= 90 || event.keyCode == 8 || event.keyCode == 13) {
                searchAnlaytics(searchfield, autoList);
                if (event.keyCode == 13) {
                    searchAnlaytics(searchfield, autoList);

                    window.open("/content/olamcorp/oil/uk/en/searchlanding.html?search=" + searchfield);
                    if (typeof redirectUrl == 'undefined') {
                         var redirectUrl = '/content/olamcorp/oil/uk/en/error/NoSearchResultsFound.html';
                    }
                   // window.location.href = redirectUrl;
                    return false
                } else {
                    var searchfieldSplit = $(this).val().split('–');
                    var searchfieldSplit1 = $(this).val().split('-');
                    var searchValue = "";
                    if (searchfieldSplit[1] != undefined) {
                        for (var i = 0; i < searchfieldSplit.length; i++) {
                            searchValue += searchfieldSplit[i] + " ";
                        }
                        searchfield = searchValue;
                    } else if (searchfieldSplit1[1] != undefined) {
                        for (var i = 0; i < searchfieldSplit1.length; i++) {
                            searchValue += searchfieldSplit1[i] + " ";
                        }
                        searchfield = searchValue;
                    }
                    e.preventDefault();
                    var request = $.ajax({
                        url: '/bin/search',
                        type: 'GET',
                        dataType: 'json',
                        cache: false,
                        data: {
                            'searchString': searchfield,
                            'param': (new Date()).getTime(),
                        },
                        success: function (response) {
                            console.log("Auto_Test", response)
                            var size = 10;
                            var list = response.slice(0, size);
                            console.log("Auto_Test1", list)
                            $("#ulCategory").children('li').remove();
                            if (list.length > 0) {
                                count = 0;
                                var analyticsAutoSuggests = "";
                                $.each(list, function () {
                                    $("#ulCategory").append("<li class='search-menu'><a  href='" + this.URL + "' class='search-menu-item container'><span class='search-title'>" + this.Title + "</span><span class='search-category'>" + this.Category + "</span></li>");
                                    analyticsAutoSuggests += this.Title + " - " + this.Category + "|";
                                });
                                var autoList = analyticsAutoSuggests;
                                if (eventCode == 13) {
                                    searchAnlaytics(searchfield, autoList);
                                }
                            } else {
                                if (typeof _satellite != "undefined") {
                                    if (!digitalData.component.search) {
                                        digitalData.component["search"] = {};
                                    }
                                    digitalData.component.search["searchTerm"] = searchfield;
                                    if (count == 0) {
                                        _satellite.track('zeroSearchResult');
                                    }
                                    count++;
                                }
                                $("#ulCategory").children('li').remove();
                                $("#ulCategory").append("<li class='no-search'><span class='no-search-content container'>No Search Result Found </span></li>");
                            }
                        },
                    });
                }
            } else {

            }
        } else {
            $("#ulCategory").hide();
            $("#ulCategory").children('li').remove();
        }
    });









    $(".arrow").click(function () {
        $("html, body").animate({
            scrollTop: 0
        }, 1000);
    });
    //added for search analytics
    /* All News page Refine Section Show Scrpit Start */
    $(document).on("click", ".refine-btn", function (e) {
        if ($(this).next().hasClass('hidden-xs') || $(this).next().hasClass('hidden-sm') || $(this).next().hasClass('hidden-md')) {
            $(this).next().removeClass('hidden-xs hidden-sm hidden-md');
            if ($('.allnewsDate-wrapper').hasClass('hidden-xs') || $(".allnewsDate-wrapper").hasClass('hidden-sm') || $(".allnewsDate-wrapper").hasClass('hidden-md')) {
                $('.allnewsDate-wrapper').removeClass('hidden-xs hidden-sm hidden-md');
            }
            $(this).removeClass('visible-xs visible-sm visible-md').hide();
        }

    });

    /* All News page Refine Section Show Scrpit End */
    var accordCount = 1;
    //$(".accordion").each(function() {
    $(".panel-group.accordion-wrapper").each(function () {
        $(this).attr("id", "accordion" + accordCount);
        $(this).find(".panel-collapse").attr("for", "accordion" + accordCount);

        if(!$(this).hasClass('ir-fin-report-accordion')) {
            $(this).find(".accordion-toggle").attr("href", "#collapse"+accordCount);
        }
        $(this).find(".panel-collapse").attr("id", "collapse"+accordCount);

        /*if(accordCount==1) {
                                                $(this).find(".panel-collapse").addClass("in");
        }
        else {
                                                $(this).find(".accordion-toggle").addClass("collapsed");
        }*/
        $(this).find(".accordion-toggle").addClass("collapsed");
        accordCount++;
    });
    $(document).on("click", ".accordion-toggle", function() {
        $(".accordion .accordion-toggle").not($(this)).addClass("collapsed").attr("aria-expanded","false");
        $(".accordion .panel-collapse").not($(this).parents(".panel-heading").next()).removeClass("in").attr("aria-expanded","false");
    });

    /* Product grid mobile accordion start */
    $(".products-list-accordion .product-list-title").click(function () {
        $(".products-list-accordion .product-list-title").not($(this)).removeClass("active");
        $(".products-list-accordion .product-list-content").not($(this).next()).slideUp();
        $(this).toggleClass("active");
        $(this).next().slideToggle();
    });
    /* Product grid mobile accordion end */

    /* twoDmap height css Start */
    $(".twoDmap.parbase").each(function () {
        var mapHeight = $(this).find("#map-canvas").height();
        $(this).height(mapHeight);
    });
    /* twoDmap height css End */
});

/* Parallax - Start */

$(function () {
    var $elements = $('.ScrollAction.notAnimated'); //contains all elements of nonAnimated class
    var $window = $(window);
    $window.on('scroll', function (e) {
        $elements.each(function (i, elem) { //loop through each element
            if ($(this).hasClass('animated')) // check if already animated
                return;
            animateMe($(this));
        });
    });
});

function animateMe(elem) {
    var winTop = $(window).scrollTop(); // calculate distance from top of window
    var winBottom = winTop + $(window).height();
    var elemTop = $(elem).offset().top; // element distance from top of page
    var elemBottom = elemTop + ($(elem).height() / 4);
    if ((elemBottom <= winBottom) && (elemTop >= winTop)) {
        // exchange classes if element visible
        $(elem).removeClass('notAnimated').addClass('animated');
    }
}

/* Parallax - End */

/* Mini Menu start */
$(document).ready(function () {

    $(".mini-menu-list li").click(function () {
        $("li").removeClass("mini-active");
        $(this).addClass("mini-active");
    });

    $(".sub-list").hide();
    $(".main-list").on("click", function () {
        $(".main-list .glyphicon").toggleClass("glyphicon-menu-right").toggleClass("glyphicon-menu-down");
        $(".sub-list").toggle();
    });
    var selected_txt = $("#mini-select li.selected_txt").text();
    //$("#mini-select li.selected_txt").hide();
    $(".main-list span").text(selected_txt);
    $("#mini-select").on("click", "li", function () {
        $(this).siblings().show();
        $(this).siblings().removeClass('selected_txt');
        $(this).addClass('selected_txt');
        $(this).hide();
        selected_txt = $(this).text();
        $(".main-list span").text(selected_txt);
        $(".sub-list").slideToggle();
    });

});
/* Mini-Menu - End */

$(document).ready(function () {
    if (window.innerWidth > 767) {
        /* bgimagecard page specific css script start */
        $(".bgimagecard").each(function () {
            if ($(this).find('.purpose-block').hasClass("full-width-pos-bot-right")) {
                var cardHeight = $(this).find('.purpose-block').height();
                if (cardHeight > 283) {
                    var bgimagecardBottom = cardHeight - 283;
                    $(this).find(".purpose-wrapper > img").css("margin-bottom", bgimagecardBottom);
                }
            }
        });
        /* bgimagecard page specific css script end */
    }
});

/* HTML video component to autoplay */
$(document).ready(function () {
    var htmlVideoList = document.getElementsByClassName('js-featureVideo')
    for (var index = 0; index < htmlVideoList.length; index++) {
        htmlVideoList[index].play();
    }
});
/* HTML video component to autoplay */

/* content restriction for cards */

$(function () {

    var charSize = 7;
    var lineHeight = 21;

    $('.ellipse-holder').each(function () {
        var $ellipsisText = $(this);
        var ellipseHolderHeight = $ellipsisText.outerHeight();
        var ellipseHolderWidth = $ellipsisText.width();
        if (ellipseHolderHeight > 180) {
            lineHeight = 22;
        } else {
            lineHeight = 21;
        }
        var titleHeight = $ellipsisText.find('h5').outerHeight(true);
        var descHeight = ellipseHolderHeight - (titleHeight);
        var charsperLine = ellipseHolderWidth / charSize;
        var totalLine = descHeight / lineHeight;
        var totalchars = Math.round((totalLine * charsperLine) * 90 / 100);
        var str = $ellipsisText.find('.ellipsis-content').text();
        var strLength = str.length;
        if (strLength > totalchars) {
            $ellipsisText.addClass("ellipsed");
            var res = str.substring(0, totalchars);
            $ellipsisText.find('.ellipsis-content').text(res);
        }
    });
});

$(document).ready(function () {

    $(".lp-dropdown-active").click(function () {
        $(this).find(".glyphicon").toggleClass("glyphicon-menu-down glyphicon-menu-up");
        $(this).next().slideToggle();
    });

    $(document).on("click", ".lp-dropdown-data a", function () {
        $(this).parents(".lp-dropdown-content").prev().find(".lp-dropdown-active-content").html(DOMPurify.sanitize($(this).html()));
        $(this).parents(".lp-dropdown-content").slideToggle();
        $(this).parents(".lp-dropdown-content").prev().find(".glyphicon").toggleClass("glyphicon-menu-down glyphicon-menu-up");
    });
});

$(function () {

    var charSize = 9;
    var lineHeight = 27.6;

    $('.ellipse-holder').each(function () {
        var $ellipsisText = $(this);
        var ellipseHolderHeight = $ellipsisText.outerHeight();
        var ellipseHolderWidth = $ellipsisText.width();
        var titleHeight = $ellipsisText.find('h3').outerHeight(true);
        var descHeight = ellipseHolderHeight - (titleHeight);
        var charsperLine = ellipseHolderWidth / charSize;
        var totalLine = descHeight / lineHeight;
        var totalchars = Math.round((totalLine * charsperLine) * 90 / 100);
        var str = $ellipsisText.find('.ellipsis-content').text();
        var strLength = str.length;
        if (strLength > totalchars) {
            $ellipsisText.addClass("ellipsed");
            var res = str.substring(0, totalchars);
            $ellipsisText.find('.ellipsis-content').text(res);
        }
    });

});

function jobAnlayticsWorldwide(jobRole, location, supplyChain) {
    console.log("testjob1");
    if (typeof _satellite != "undefined") {
        if (!digitalData.careers) {
            digitalData["careers"] = {};
            console.log("Job Error", digitalData.careers)
        }
        console.log("Main-test1")
        digitalData.careers.jobRole= jobRole;
        //digitalData.careers.location = location;
        digitalData.careers.supplyChain = supplyChain;
        _satellite.track('jobApplication')
    }
}

$(".Worldwide.careers").click(function (e) {
    console.log("Main-test")
    let jobRole = "New Job"
    let location = "Worldwide"
    let supplyChain = "Olam"
    console.log("Job Test", supplyChain + location + jobRole);
    jobAnlayticsWorldwide(jobRole, location, supplyChain)
});

$(".Australia.careers").click(function (e) {
    console.log("Main-test")
    let jobRole = "New Job"
    let location = "Australia"
    let supplyChain = "Olam"
    console.log("Job Test", supplyChain + location + jobRole);
    jobAnlayticsWorldwide(jobRole, location, supplyChain)
});
$(".USA.careers").click(function (e) {
    console.log("Main-test")
    let jobRole = "New Job"
    let location = "USA"
    let supplyChain = "Olam"
    console.log("Job Test", supplyChain + location + jobRole);
    jobAnlayticsWorldwide(jobRole, location, supplyChain)
});
$(".Europe.careers").click(function (e) {
    console.log("Main-test")
    let jobRole = "New Job"
    let location = "Europe"
    let supplyChain = "Olam"
    console.log("Job Test", supplyChain + location + jobRole);
    jobAnlayticsWorldwide(jobRole, location, supplyChain)
});


// All variables declared
(function () {
    const metaObject = {};
    const metas = document.getElementsByTagName('meta');
    const windowLocation = window.location.href;
    const serverUrl = windowLocation.substring(windowLocation.indexOf('//')+2).split("/")[0];

    for (let i = 0; i < metas.length; i++) {
            let property = metas[i].getAttribute('property');
            let content = metas[i].getAttribute('content');
            let name = metas[i].getAttribute('name');
                if(property != undefined){
                    metaObject[property] = content;
                }
                if(name != undefined){
                    metaObject[name] = content;
                }
  }
    window.analyticsData = {
        ...metaObject,
        "serverUrl": serverUrl,
        "url": windowLocation
    };
})();


// All functions declared
(function () {
    const allLinks = document.getElementsByTagName("a");
 
    for (let i = 0; i < allLinks.length; i++) {
        if(allLinks[i].parentElement.classList.contains("list-social")){
            allLinks[i].addEventListener('click', function(e){
                e.preventDefault();
                const attribute = e.target.parentElement.getAttribute("target");
                const target = attribute ? attribute: "_self";
                const currentLink = e.target.closest("a").getAttribute("href")
                analyticsOnClickSocialMedia(e, function(){
                    window.open(currentLink, target)
                })
            });

        } else if(allLinks[i].getAttribute("href") &&
                  allLinks[i].getAttribute("href") != null &&
                  !allLinks[i].closest(".results")
                  ){
            allLinks[i].addEventListener('click', function(e){
                e.preventDefault();
                const attribute = e.target.closest("a").getAttribute("target");
                const target = attribute ? attribute: "_self";
                const currentLink = e.target.closest("a").getAttribute("href");
                const currentEvent = e.target.closest("a").getAttribute("data-link-text") || e.target.closest("a").innerText;
                analyticsOnClickEvent(e,currentEvent, function(){
                    window.open(currentLink, target)
                })
            });
            }
        }

  })();

// analyticsWindowOnLoad function
function analyticsWindowOnLoad(){
    window.adobeDataLayer = window.adobeDataLayer || [];
    if(analyticsData.isErrorPage == "true"){
        window.adobeDataLayer.push({
            "event": "error",
            "error": [{
                "errorCode": (analyticsData.subcategory1 ? analyticsData.subcategory1 : ""),
                "errorField": "N/A",
                "errorDescription": (analyticsData.primarycategory ? analyticsData.primarycategory : "")
            }],
            "eventInfo": {
                "eventType": "web.webInteraction.linkClicks"
            },
            "web": {
                "webPageDetails": {
                    "name": (analyticsData.pageName ? analyticsData.pageName : ""),
                    "URL": (analyticsData.url ? analyticsData.url : ""),
                },
                "webLinkDetails": {
                    "eventName": "Error"
        } }
        });
    } else{
        window.adobeDataLayer.push({
            "event": "pageView",
            "eventInfo": {
                        "eventType": "web.webpagedetails.pageViews"
                   },
            "web": {
                   "webPageDetails": {
                                     "name": (analyticsData.pageName ? analyticsData.pageName : ""),
                                     "URL": (analyticsData.url ? analyticsData.url : ""),
                                     "server": (analyticsData.serverUrl ? analyticsData.serverUrl : ""),
                                     "title": (analyticsData['og:title'] ? analyticsData['og:title'] : ""),
                                     "primarycategory": (analyticsData.primarycategory ? analyticsData.primarycategory : ""),
                                     "subcategory1": (analyticsData.subcategory1 ? analyticsData.subcategory1 : ""),
                                     "subcategory2": (analyticsData.subcategory2 ? analyticsData.subcategory2 : ""),
                                     "subcategory3": (analyticsData.subcategory3 ? analyticsData.subcategory3 : "")
                   },
                   
            ...((analyticsData.template === "article-template" || analyticsData.template === "article-page-template") && {
            "article": {
                            "name": (analyticsData.articleName ? analyticsData.articleName : ""),
                            "date": (analyticsData.articleDate ? analyticsData.articleDate : ""),
                            "category": (analyticsData.articleCategory ? analyticsData.articleCategory : "")
                            }
                    })
    
                    },
        
                });
    }
    }

// window analyticsOnClickEvent function
function analyticsOnClickEvent(e,currentEvent, callback){
    const _this = e.target;
    const componentVal = analyticsComponentName(_this);
    window.adobeDataLayer = window.adobeDataLayer || [];
    window.adobeDataLayer.push({
    "event": "click",
    "eventInfo": {
    "eventType": "web.webInteraction.linkClicks"
    },
    "web": {
           "webPageDetails": {
                             "name": (analyticsData.pageName ? analyticsData.pageName : ""),
                             "URL": (analyticsData.url ? analyticsData.url : "")
           },
           "webLinkDetails": {
                            "eventName": (currentEvent!= undefined ? currentEvent : ""),
                            "componentName": componentVal
            
            },
    }
  });
  callback && callback();
  
}

// window analyticsOnClickSocialMedia function
function analyticsOnClickSocialMedia(e, callback){
    let socialMediaNameElement = e.target.parentElement.querySelector("img").getAttribute("alt");
    let socialMediaName = socialMediaNameElement ? socialMediaNameElement : "";
    window.adobeDataLayer = window.adobeDataLayer || [];
    window.adobeDataLayer.push({
        "event": "socialMediaClick",
        "socialMedia": {
            "name": socialMediaName
               }
    });
    callback && callback();
}

// window analyticsFormStartEvent function
function analyticsFormStartEvent(formName, eventName, compName){
    window.adobeDataLayer = window.adobeDataLayer || [];
        window.adobeDataLayer.push({
            "event": "formStart",
            "form": {
                "name": formName
            },
            "eventInfo": {
                "eventType": "web.webInteraction.linkClicks"
            }, 
            "web": {
                "webPageDetails": {
                    "name": (analyticsData.pageName ? analyticsData.pageName : ""),
                    "URL": (analyticsData.url ? analyticsData.url : "")
                    },
                "webLinkDetails": {
                    "eventName": (eventName!= undefined ? eventName : ""),
                    "componentName": (compName != undefined ? compName : "")
                    }
            }
        });
}

// window analyticsFormCompleteEvent function
function analyticsFormCompleteEvent(formName, clickedButtonName, compName){
    window.adobeDataLayer = window.adobeDataLayer || [];
    window.adobeDataLayer.push({
        "event": "formComplete",
        "form": {
            "name": formName
        },
        "eventInfo": {
            "eventType": "web.webInteraction.linkClicks"
        }, 
        "web": {
            "webPageDetails": {
                "name": (analyticsData.pageName ? analyticsData.pageName : ""),
                "URL": (analyticsData.url ? analyticsData.url : "")
                },
            "webLinkDetails": {
                "eventName": (clickedButtonName != undefined ? clickedButtonName : ""),
                "componentName": (compName != undefined ? compName : "")
                }
        }
    });
}

// window analyticsFormAbandonEvent function
function analyticsFormAbandonEvent(formName, eventName, compName){
    window.adobeDataLayer = window.adobeDataLayer || [];
    window.adobeDataLayer.push({
        "event": "formAbandon",
        "form": {
            "name": formName
        },
        "eventInfo": {
            "eventType": "web.webInteraction.linkClicks"
        }, 
        "web": {
            "webPageDetails": {
                "name": (analyticsData.pageName ? analyticsData.pageName : ""),
                "URL": (analyticsData.url ? analyticsData.url : "")
                },
            "webLinkDetails": {
                "eventName": (eventName!= undefined ? eventName : ""),
                "componentName": (compName != undefined ? compName : "")
                }
        }
    });
}

// window analyticsFormErrorEvent function
function analyticsFormErrorEvent(compName, eventName, errorList){
    window.adobeDataLayer = window.adobeDataLayer || [];
    window.adobeDataLayer.push({
        "event": "error",
        "error": errorList,
        "eventInfo": {
            "eventType": "web.webInteraction.linkClicks"
        },
        "web": {
            "webPageDetails": {
                "name": (analyticsData.pageName ? analyticsData.pageName : ""),
                "URL": (analyticsData.url ? analyticsData.url : ""),
            },
            "webLinkDetails": {
                "eventName": (eventName != undefined ? eventName : ""),
                "componentName": (compName != undefined ? compName : "")
    } }
    });
}

// window analyticsFormErrorEvent function
function analyticsNewsFilterTracking(filterObject, clickEvent, compName){
    window.adobeDataLayer = window.adobeDataLayer || [];
    window.adobeDataLayer.push({
        "event": "filterUsage",
        "filter": {
        "filterName": analyticsData.pageName + " - " + compName? analyticsData.pageName + " - " + compName : "",
        "filtersApplied": filterObject        
        },
        "eventInfo": {
            "eventType": "web.webInteraction.linkClicks"
            },
        "web": {
            "webPageDetails": {
                "name": (analyticsData.pageName ? analyticsData.pageName : ""),
                "URL": (analyticsData.url ? analyticsData.url : "")
            },
            "webLinkDetails": {
                "eventName": clickEvent,
                "componentName": compName
            }}
    });
}

// window analyticsSuggestedSearchTerm function
function analyticsSuggestedSearchTerm(compName, searchTermValue){
    window.adobeDataLayer = window.adobeDataLayer || [];
    window.adobeDataLayer.push({
        "event": "searchSuggestionClick",
        "search": {
            "suggestedSearchTerm": (searchTermValue != undefined ? searchTermValue : "")
        },
        "eventInfo": {
        "eventType": "web.webInteraction.linkClicks"
        }, 
        "web": {
            "webPageDetails": {
                "name": (analyticsData.pageName ? analyticsData.pageName : ""),
                "URL": (analyticsData.url ? analyticsData.url : "")
            },
            "webLinkDetails": {
                "eventName": "Search Suggestion Click",
                "componentName": (compName != undefined ? compName : "")
            }
        } 
    });
}

// window analyticsSuggestedSearchResult function
function analyticsSuggestedSearchResult(compName, searchTerm, searchResultNumber){
    window.adobeDataLayer = window.adobeDataLayer || [];
    window.adobeDataLayer.push({
        "event": "search",
        "search": {
            "searchTerm": (searchTerm != undefined? searchTerm : ""),
            "numberOfSearchResults": (searchResultNumber != undefined? searchResultNumber : "")
        },
        "eventInfo": {
            "eventType": "web.webInteraction.linkClicks"
            }, 
        "web": {
                "webPageDetails": {
                    "name": (analyticsData.pageName ? analyticsData.pageName : ""),
                    "URL": (analyticsData.url ? analyticsData.url : "")
                },
                "webLinkDetails": {
                    "eventName": "Search Results Load",
                    "componentName": (compName != undefined? compName : "")
                }
            }
        });
}

// window analyticsSearchClickThrough function
function analyticsSearchClickThrough(compName, clickedResultIndex, callback){
    window.adobeDataLayer = window.adobeDataLayer || [];
    window.adobeDataLayer.push({
        "event": "searchResultsClickthrough",
        "search": {
            "searchRank": (clickedResultIndex != undefined? clickedResultIndex : "")
        }, 
        "eventInfo": {
            "eventType": "web.webInteraction.linkClicks"
            }, 
        "web": {
                "webPageDetails": {
                    "name": (analyticsData.pageName ? analyticsData.pageName : ""),
                    "URL": (analyticsData.url ? analyticsData.url : "")
                },
                "webLinkDetails": {
                    "eventName": "Search Results Clickthrough",
                    "componentName": (compName != undefined? compName : "")
                }
            }
    });
    callback && callback();
}

// analyticsComponentName function
function analyticsComponentName(current){
    let componentName = "";
    if(current.closest("[data-component]")){
        componentName = current.closest("[data-component]").getAttribute("data-component");
    }
    return componentName
}
window.addEventListener("load", analyticsWindowOnLoad);


$(document).ready(function() {
    //  To hide footer subscribe banner
    $(".close-btn").click(function() {
        $(".notification").hide();
    });
});

function subscribeRecaptchaCallback(){
    var v = grecaptcha.getResponse(window.subscribeWidgetId);
    if(v.length == 0){
        $("#subscribe_captcha_error").addClass("captchaError");
        document.getElementById('subscribe_captcha_error').style.display='block';
        return false;
    } else {
        $("#subscribe_captcha_error").removeClass("captchaError");
        document.getElementById('subscribe_captcha_error').style.display='none';
        return true;
    }
}

    $(function() {
        $("#subscribe").on('submit', function(event) {
        	event.preventDefault();
        	return false;
        }).validate({
            rules: {
                firstname: {
                    required: true,
                    regex: /^[a-zA-Z0-9!?@#\$%£\"'\/\^\&*\)\(+=._-]+([a-zA-Z0-9\s!?@#\$%£\"'\/\^\&*\)\(+=._-]+)+$/
                },
                lastname: {
                    required: true,
                    regex: /^[a-zA-Z0-9!?@#\$%£\"'\/\^\&*\)\(+=._-]+([a-zA-Z0-9\s!?@#\$%£\"'\/\^\&*\)\(+=._-]+)+$/
                },
                country: {
                    required: true,
                },
                industry: {
                    required: true,
                },
                job: {
                    required: true,
                },
                checkbox: {
                    required: true,
                },
                //  googlecapcha: {
                //     required: true,
                // },
                email: {
                    required: true,
                    email: true,
                }
            },
            // Specify validation error messages
            messages: {

                 firstname: {
                    required: "First Name is required",
                    regex: "Please enter a valid First Name"

                },
                lastname: {
                    required: "Last Name is required",
                    regex: "Please enter a valid Last Name"

                },
                country: {
                    required: "Please select Country",
                },
                industry:

                {
                    required: "Please select Industry",
                },
                job: {
                    required: "Please select Job Position",
                },
                checkbox: {
                    required: "Please agree to the privacy policy to proceed",
                },
                // googlecapcha: {
                //     required: "Please fill",
                // },
                email: {
                    required: "Email is required",
                    email: "Please enter a Valid Email Address",
                }
            },
            // Make sure the form is submitted to the destination defined
            // in the "action" attribute of the form when valid
            
            submitHandler: function(form) {
                const recaptcha = subscribeRecaptchaCallback();
                const subscribeStatus = $("#subscribe").valid();
                const errorCaptchaMsg = $("#subscribe_captcha_error").text().trim();
                const componentName =  $("#submit").parents("#formSubscribeModal").attr("data-component");
                const eventName = $("#submit").attr("name");
                const formInputsVal = {
                    "errorCode": "N/A",
                    "errorField": "Captcha",
                    "errorDescription": errorCaptchaMsg
                } 
                if(recaptcha){
                    if(subscribeStatus){
                        sendSubscriptionList();
                    }
                } else{
                    analyticsFormErrorEvent(componentName, eventName, formInputsVal);
                }
            },

            invalidHandler: function(form, validator) {
                subscribeRecaptchaCallback();
                let formInputs = validator.errorList;
                if($("#subscribe_captcha_error").hasClass("captchaError")){
                let errorCaptchaMsg = $("#subscribe_captcha_error").text().trim();
                    formInputs.push({message: errorCaptchaMsg, element: {name:"Captcha"}})
                }
                let formInputsVal = [];
                const componentName =  $(this).parents("#formSubscribeModal").attr("data-component");
                const eventName = $("#submit").attr("name");
                formInputs.forEach(function(ele) { 
                    formInputsVal.push({
                        "errorCode": "N/A",
                        "errorField": ele.element.name,
                        "errorDescription": ele.message
                    })
                });                
                analyticsFormErrorEvent(componentName, eventName, formInputsVal);                    
            },
            onkeyup: function(element) {
                if (element.id == 'email') {
                    return false;
                }
            }
        });

                             var date = new Date();
                  var timestamp = date.getTime();


      function subscribeResultIterate(responseString, type) {
        var result = "";
          if (responseString != "") {
              //var resultsIteration = responseString.split(",");
              for (var index = 0 ; index < responseString.length; index++) {
                  if (type== "Success") {
                      result += "<div class=\"alert alert-success\"><strong>Success!</strong> "+ responseString[index] +"</div>";
                  } else if (type== "Failure") {
                      result += "<div class=\"alert alert-danger\"><strong>Failure!</strong> "+ responseString[index] +"</div>";
                  }
              }
          }
          return result;
      }

      function subscribeResult(response) {
          var result = "";
          if (response.Success !== undefined) {
              result += subscribeResultIterate(response.Success, "Success");
          }
          if (response.Failure !== undefined) {
              result += subscribeResultIterate(response.Failure, "Failure");
          }

           var ResponeResultsubcribepage ="<div class=\"panel panel-info js-subscribeResult\"><div class=\"panel-heading\"><b>Thank you for sharing your details. We will keep you up-to-date with the latest Olam news and information. In the meantime, why not explore our products and services, or read about what we’ve been doing recently in our news section</b></div><div class=\"panel-body\"><button type=\"button\" id=\"btntakehome\" class=\"btn btn-primary  pull-right\">Take me to home page</button></div></div>"

          var subcribeResponeResult = "<div class=\"panel panel-info js-subscribeResult\"><div class=\"panel-heading\"><b>Thank you for your request. Your subscription request generated the following results;</b></div><div class=\"panel-body\">"+ result +"<button type=\"button\" id=\"btnOK\" class=\"btn btn-primary  pull-right\">OK</button></div></div>";


    if (window.location.href.indexOf('subscribe.html') > -1) {
      console.log("your url contains the name subscribe.html");

          $("#subscribe").append(ResponeResultsubcribepage);
                    let formName = $("#subscribe").attr("name");
                    let clickedButtonName = $("#subscribe #submit").attr("name");
                    let compName = $("#formSubscribeModal").attr("data-component");
                    analyticsFormCompleteEvent(formName, clickedButtonName, compName);
                           
}
          else

              $("#subscribe").append(DOMPurify.sanitize(subcribeResponeResult));
                    let formName = $("#subscribe").attr("name");
                    let clickedButtonName = $("#subscribe #submit").attr("name");
                    let compName = $("#formSubscribeModal").attr("data-component");
                    analyticsFormCompleteEvent(formName, clickedButtonName, compName);


          $("#btntakehome").on("click", function() {
              $('#subscribe > .form-group').show();
              $(".js-subscribeResult").remove();
              $("#subscribe").trigger('reset');
              grecaptcha.reset();
              var go_to_url = '/content/olamcorp/oil/uk/en.html';
              var go_to_sit_url = 'https://sit-msm.olamgroup.com/';
              var go_to_stage_url = 'https://stg-msm.olamgroup.com/';
              var go_to_live_url = 'https://www.olamgroup.com/';
              if (window.location.host == "10.101.230.68:4502") {
                window.open(go_to_url, '_blank');
              }
              else if (window.location.host == "sit-msm.olamgroup.com") {
                window.open(go_to_sit_url, '_blank');
              }
              else if (window.location.host == "stg-msm.olamgroup.com") {
                window.open(go_to_stage_url, '_blank');
              }
              else {
                window.open(go_to_live_url, '_blank');
              }
          });


          $("#btnOK").on("click", function() {

              $('#subscribe > .form-group').show();
              $(".js-subscribeResult").remove();
              $("#subscribe").trigger('reset');
              grecaptcha.reset();
              var selectObj = $("select > option[hidden]");
              var selectTextbox = ["Select country", "Select industry", "Select job position"];
              $.each(selectObj, function(index, value) {
                  $(this).text(selectTextbox[index]);
              });
              $(".subscribe-modal-header .close-btn-modal").click();
          });
      }

                  function sendSubscriptionList() {
                	  let subscribeArr = [];
                      let subscribeCheckedItems = $('.subs-list :checkbox:checked');
                      if( subscribeCheckedItems.length > 0) {
                        for(let counter = 0; counter <  subscribeCheckedItems.length; counter++) {
                          subscribeArr.push({'id' : subscribeCheckedItems[counter].id, 'value' : subscribeCheckedItems[counter].value});
                        }
                      }
                      let subscribeApiUrl = $('#formSubscribeModal').attr('data-subscribe-api-url');
                      $.ajax({
                          url: subscribeApiUrl,
                          type: "POST",
                          dataType: "json",
                          cache: false,
                          data: {
                              email: $("#subscribeEmail").val(),
                              firstName: $("#firstname").val(),
                              lastName: $("#lastname").val(),
                              country: $("#country option:selected").val(),
                              industry: $("#industry option:selected").val(),
                              jobPosition: $("#job option:selected").val(),
                              agree: $("#agree option:selected").val(),
                              subscribe: subscribeArr.length === 0 ? "" : JSON.stringify(subscribeArr),
                              timestamp: timestamp,
                              g_recaptcha_response: grecaptcha.getResponse(window.subscribeWidgetId)  
                          },
                          beforeSend: function() {
                            console.log("Subscribe before Ajax Call");
                          }, 
                          success: function(response) {
                            $(".js-subscribeResult").remove();
                            subscribeResult(response);
                            $('#subscribe > .form-group').hide();
                                grecaptcha.reset(window.subscribeWidgetId);
                            }
                        });
                  }



    });

$(document).ready(function() {
    let eventName;
    let formName;
    let compName;

    $("#subscribee").on('click', function(e) {
        eventName = e.target.closest("a").innerText;
        formName = $("#subscribe").attr("name");
        compName = $("#formSubscribeModal").attr("data-component");
        analyticsOnClickEvent(e, eventName)
        analyticsFormStartEvent(formName, eventName, compName);
    });

    $(".notification__action a").on('click', function(e) {
        eventName = e.target.closest("a").innerText;
        formName = $("#subscribe").attr("name");
        compName = $("#formSubscribeModal").attr("data-component");
        analyticsFormStartEvent(formName, eventName, compName);
    })

    
    $(".contact-modal-header .close-btn-modal").on('click', function() {
        eventName = $(this).attr("name");
        formName = $("#contactform").attr("name");
        compName = $("#contactUsForm").attr("data-component");
        analyticsFormAbandonEvent(formName, eventName, compName);
    })

    $(".subscribe-modal-header .close-btn-modal").on('click', function() {
        eventName = $(this).attr("name");
        formName = $("#subscribe").attr("name");
        compName = $("#formSubscribeModal").attr("data-component");
        analyticsFormAbandonEvent(formName, eventName, compName);
    })

    // reset form values once the modal is closed
    $('#contact_popup').on('hidden.bs.modal', function() {
        document.getElementById('contactform').reset()
        grecaptcha.reset(window.contactWidgetId);
        $("label.error").remove();
        $("#contact_captcha_error").hide();
        $(this).find('.valid').removeClass('valid');
        $(this).find('.error').removeClass('error');
    });

    // reset form values once the modal is closed
    $('#formSubscribeModal').on('hidden.bs.modal', function() {
        $(this).find('form').trigger('reset');
        grecaptcha.reset(window.subscribeWidgetId);
        $(".error").next('label').remove();
        $(this).find('.error').removeClass('error');
        $(".js-subscribeResult").remove();
        $('#subscribe > .form-group').show();
    });

    $("#subscribe [type='submit']").on('click', function() {

        $("select option[hidden]").text("");
    });
       $('#formSubscribeModal input[type="text"], #formSubscribeModal input[type="email"]').focus(function() {
        $(this).next('label').remove();
    });


    $('#formSubscribeModal input[type="text"], #formSubscribeModal input[type="namefnln"]').focus(function() {
        $(this).next('label').remove();
    });


    /*$('input[type="email"]').on('blur', function(e) {
        if ($(this).next().hasClass('error')) {
            $(this).val('');
        }
    });
      $('input[type="namefnln"]').on('blur', function(e) {
        if ($(this).next().hasClass('error')) {
            $(this).val('');
        }
    });*/


    $('#formSubscribeModal select').on("keydown", function(e) {
        if(e.which==38 || e.which==40) {
                                           if ($(this).next().hasClass('error')) {
                $(this).next().html('');
            }
        }
    }); 
 });


/* Subscribe overlay validation - End */

/* SVG conversion Start */
/*
 * Replace all SVG images with inline SVG
 */
$(function() {
    $('.products-list img.img-responsive').each(function() {
        var $img = $(this);
        var imgID = $img.attr('id');
        var imgClass = $img.attr('class');
        var imgURL = $img.attr('src');
        $.get(imgURL, function(data) {
            var santized_data = DOMPurify.sanitize(data);
            // Get the SVG tag, ignore the rest
            var $svg = $(santized_data).find('svg');
            // Add replaced image's ID to the new SVG
            if (typeof imgID !== 'undefined') {
                $svg = $svg.attr('id', imgID);
            }
            // Add replaced image's classes to the new SVG
            if (typeof imgClass !== 'undefined') {
                $svg = $svg.attr('class', imgClass + ' replaced-svg');
            }
            // Remove any invalid XML tags as per http://validator.w3.org
            $svg = $svg.removeAttr('xmlns:a');
            // Replace image with new SVG
            $img.replaceWith($svg);
        }, 'xml');
    });
});
/* SVG conversion End */
$(function() {
    $('.mobile-menubar-green img.mobile-menu').each(function() {
        var $img = $(this);
        var imgID = $img.attr('id');
        var imgClass = $img.attr('class');
        var imgURL = $img.attr('src');
        $.get(imgURL, function(data) {
            var santized_data = DOMPurify.sanitize(data);
            // Get the SVG tag, ignore the rest
            var $svg = $(santized_data).find('svg');
            // Add replaced image's ID to the new SVG
            if (typeof imgID !== 'undefined') {
                $svg = $svg.attr('id', imgID);
            }
            // Add replaced image's classes to the new SVG
            if (typeof imgClass !== 'undefined') {
                $svg = $svg.attr('class', imgClass + ' replaced-svg');
            }
            // Remove any invalid XML tags as per http://validator.w3.org
            $svg = $svg.removeAttr('xmlns:a');
            // Replace image with new SVG
            $img.replaceWith($svg);
        }, 'xml');
    });
});

$(document).ready(function () {
    let anchorNavTopOffset = 0;
    let prevScroll = 0;
    let currentScroll = 0;

    $(".olam-anchor-nav__wrapper a").on("click", function (event) {
        event.preventDefault();
        const navigateTo = DOMPurify.sanitize($(this).attr('href').substring(1));
        let isSticky = $(this).parents('.olam-anchor-nav__wrapper').hasClass('stickyAnchor');
        if ($(`[id='${navigateTo}']`).length > 0) {
            let topPosition = 0;
            let sidenavHeight = $('.side-nav').height();
            let anchorNavHeight = $('.olam-anchor-nav__wrapper').height();
            if (isSticky) {
                topPosition = $(`[id='${navigateTo}']`).parent().position().top - (sidenavHeight + anchorNavHeight);
            } else {
                topPosition = $(`[id='${navigateTo}']`).parent().position().top - 2 * (sidenavHeight + anchorNavHeight);
            }
            $("html, body").animate({
                "scrollTop": topPosition
            });
        }

    });

    if ($('.olam-anchor-nav__wrapper')[0])
        anchorNavTopOffset = $('.olam-anchor-nav__wrapper')[0].offsetTop;

    $(document).scroll(function () {
        let sidenavHeight = $('.side-nav').height();
        currentScroll = $(window).scrollTop();
        let delta = currentScroll - prevScroll;
        if (delta < 0) {
            if (window.pageYOffset >= anchorNavTopOffset - sidenavHeight - sidenavHeight) {
                $('.olam-anchor-nav__wrapper').addClass('stickyAnchor');
                $('.stickyAnchor').css('top', sidenavHeight);
            }
            else {
                $('.olam-anchor-nav__wrapper').removeClass('stickyAnchor');
                $('.stickyAnchor').css('top', 0);
            }
        } else {
            $('.olam-anchor-nav__wrapper').removeClass('stickyAnchor');
            $('.stickyAnchor').css('top', 0);
        }
        prevScroll = currentScroll;
    });
});

/* Board of Directors - page */
/* Code for 3 column structure in lg(Portrait and landscape), md(Portrait and landscape) and sm(landscape) devices. 2 column structure in sm(Portrait) and xs devices */
$(document).ready(function() {
	var boardMembers = $('.tile-img-block');

	var boardMembersIndex = 1;
	$.each(boardMembers, function( index, value ) {
	  if (boardMembersIndex % 2 == 0) {
		$(this).parent().after("<div class=\"clearfix visible-sm\"></div>");
	  }
	  if (boardMembersIndex % 3 == 0) {
		$(this).parent().after("<div class=\"clearfix visible-md visible-lg\"></div>");
	  }	  
	  boardMembersIndex++;
	});
});
/* Sustainable Supply Chains - page */
/* Code for 4 column carousel structure in lg(Portrait and landscape), md(Portrait and landscape) and sm(landscape) devices. 
   2 column structure in sm(Portrait) and 1 column structure in xs devices */
$(document).ready(function() {
    // responsive slick carousel
    var multiCarousel = $(".carousel");
    $(".four-tile-slider").not('.slick-initialized').slick({
      adaptiveHeight: true,
      dots: true,
      arrows: true,
      cssEase: "linear",
      speed: 0,
      slidesToShow: 4,
      slidesToScroll: 4,
      responsive: [{
        breakpoint: 1024, // width < 1024
        settings: {
            slidesToShow: 3,
            slidesToScroll: 3
          }
        }, {
        breakpoint: 900, // width < 768
        settings: {
            slidesToShow: 2,
            slidesToScroll: 2
          }
        }, {
        breakpoint: 768, // width < 768
        settings: {
            slidesToShow: 1,
            slidesToScroll: 1
          }
        }, {
        breakpoint: 569, // max-width < 569
        settings: {
            slidesToShow: 1,
            slidesToScroll: 1
          }
        }]
    });

    addCardCarousal();
    setCardCarouselArrow();

    /* code to adjust slick carousel height and slick dots height */
    function adjustSlickHeight() {
      
      var currentHeight = $(".four-tile-slider .card-wrapper.news-cards").innerHeight();
      currentHeight = currentHeight + 35;
      $('.four-tile-slider').css({"height" : currentHeight+'px'});
      
     var IPAD = 676;
     var $win = $(window);

      if ($win.outerWidth() > IPAD) {
         $('#fourTileSustCarousel .slick-dots').css({"height" : '20px', "margin-bottom": "2px"});
      }
    }
    
    setTimeout(function(){
      adjustSlickHeight();
    }, 2000);

    $(window).on('resize orientationchange', function() {
      $('.ogs-card__content').slick('resize');
      $('.four-tile-slider').slick('resize');
      addCardCarousal();
      adjustSlickHeight();
      setCardCarouselArrow();
    });

});
function setCardCarouselArrow() {
  setTimeout(() => {
      $('.four-tile-slider').each((idx, element) => {
          const $parent = element;
          if($('.slick-dots', $parent).length) {
              $('.slick-prev', $parent).css('left', $('.slick-dots li:first-child', $parent).position().left - 25);
              $('.slick-next', $parent).css('left', $('.slick-dots li:last-child', $parent).position().left + 22);
          }
      });
  }, 100);

}

function addCardCarousal() {
  $(".ogs-card__content").not('.slick-initialized').slick({
    adaptiveHeight: true,
    dots: true,
    arrows: true,
    cssEase: "linear",
    slidesToShow: 3,
    slidesToScroll: 3,
    autoplay: $('.ogs-card__content').attr('data-auto-scroll') === 'true',
    autoplaySpeed: 5000,
    infinite: true,
    responsive: [
      {
        breakpoint: 992,
        settings: 'unslick'
      }]
  });
}

/* Sustainable Supply Chains - page */
/* Code for 4 column carousel structure in lg(Portrait and landscape), md(Portrait and landscape) and sm(landscape) devices. 
   2 column structure in sm(Portrait) and 1 column structure in xs devices */
$(document).ready(function() {
    // slick carousel
    var multiCarousel = $(".carousel");
    $(".three-tile-slider").not('.slick-initialized').slick({
        adaptiveHeight: true,
        dots: true,
        arrows: false,
        speed: 0,
        cssEase: "linear",
        slidesToShow: 3,
        slidesToScroll: 3,
        responsive: [{
            breakpoint: 1024, // width < 1024
            settings: {
                slidesToShow: 3,
                slidesToScroll: 3
            }
        }, {
            breakpoint: 900, // width < 768
            settings: {
                slidesToShow: 2,
                slidesToScroll: 2
            }
        }, {
            breakpoint: 768, // width < 768
            settings: {
                slidesToShow: 1,
                slidesToScroll: 1
            }
        }, {
            breakpoint: 569, // max-width < 569
            settings: {
                slidesToShow: 1,
                slidesToScroll: 1
            }
        }]
    });

    /* 
     *  code to adjust slick carousel height and slick dots height
     */
    function adjustSlickHeight() {
        var IPAD = 676;
        var $win = $(window);
        if ($win.outerWidth() > IPAD) {
            $('#fourTileSustCarousel .slick-dots').css({
                "height": '17px'
            });
            $('.js-kpi-carousel .slick-list').eq(1).css({
                "margin-bottom": "120px"
            });
        }
    }

    setTimeout(function() {
        adjustSlickHeight();
    }, 2000);

    $(window).on('resize orientationchange', function() {
        $('.three-tile-slider').slick('resize');
        adjustSlickHeight();
    });
});
$(document).ready(function () {
	$('.text-img-carousel-slider').not('.slick-initialized').slick({
			dots: true,
			infinite: true,
			autoplay: $('.text-img-carousel-slider').attr('data-auto-scroll') === 'true',
			autoplaySpeed: 5000,
			slidesToShow: 1,
			slidesToScroll: 1,
			cssEase: 'linear',
			arrows: true	
		});
		setTextImageCarouselSliderArrow(); 
});
function setTextImageCarouselSliderArrow() {
	setTimeout(() => {
		$('.text-img-carousel-slider').each((idx, element) => {
			const $parent = element;
			if($('.slick-dots', $parent).length) {
				$('.slick-prev', $parent).css('left', $('.slick-dots li:first-child', $parent).position().left - 25);
				$('.slick-next', $parent).css('left', $('.slick-dots li:last-child', $parent).position().left + 22);
			}
		});
	}, 100);
}
$(window).on('resize orientationchange', function() {
	if($('.text-img-carousel-slider').length)
	setTextImageCarouselSliderArrow();
});
$(document).ready(function() {

    var playerids = [];
    var totl_stack = $('.card-event-vdo-child').length;
    $("span#stack_count_toal").append(totl_stack);
    $("span#stack_count_present").append(1);



    $(".card-event-vdo-parent:eq( 0 )", ".card-img-container-vdo").show();

    $(".card-event-vdo-child:first-child", ".card-img-container-vdo").addClass("theme--based--highlighted--stack");

    if (totl_stack > 3) {

        //$(".child-right").attr("id", "stack-scroll");
        $(".child-right").addClass( "theme-based-scroll-bar-vertical");

    }

    $(".card-event-vdo-parent").each(function(index, i) {
        var idattrValDis = "stack_id_" + index;
        $(this).attr("id", idattrValDis);
    });

    $(".card-event-vdo-child").each(function(index, i) {
        var idattrVal = "stack_id_" + index;
        $(this).attr("id", idattrVal);
    });

    $(".display-video-vdo").each(function(index, i) {
        var idattrValU = "youtube_id_" + index;
        $(this).attr("id", idattrValU);
    });
    $(".popular").each(function(index, i) {
        var idattrValU_pop = "popular_id_" + index;
        $(this).attr("id", idattrValU_pop);
    });

    $(".card-event-vdo-child").click(function() {

        var $parent = $(this).closest(".card-img-container-vdo");
        console.log("***********************", $parent);
        var $container = $(".card-event-vdo-parent", $parent);
        var clickedId = DOMPurify.sanitize($(this).attr("id"));

        $(".card-event-vdo-child", $parent).removeClass("theme--based--highlighted--stack");
        $(this).addClass("theme--based--highlighted--stack");

        $container.hide();
        $("[id='" + clickedId + "']", $parent).show();



        playerids.push(clickedId);
        console.log("playerids****************", playerids);
        var res = playerids.slice(-2)[0];
        var previousId = "#" + res;
        console.log("_______________________", previousId);
        
        var deactId = DOMPurify.sanitize($(previousId).find(".display-video-vdo")[0].id);
        var deactIdPlus = "#" + deactId;
        $(deactIdPlus).attr("src", $(deactIdPlus).attr("src"));
        $(deactIdPlus).get(0).pause();

        var showValue = clickedId.split('_')[2];
        var increment = 1;
        var showpresent = parseFloat(showValue) + parseFloat(increment);
    });



    var windowWidth = $(window).width();

    if (windowWidth <= 767) {

        $(".card-bar-vdo").removeClass("theme-based-bottom-bar");
        $(".child-right").removeClass("theme-based-scroll-bar-vertical");

        $(".boxslide").attr('class', 'popular');

    } 

});


$(function() {
    if($('.popular') && $('.popular').length) {
        $('.popular').bxSlider({
            slideWidth: 900,
            minSlides: 2,
            maxSlides: 3,
            moveSlides: 1,
            pager: false,
            auto: false
        });
    }
});
$(document).ready(function() {
	// code to control the height of card when content is more
    function adjustFullWidthImageCardHeight() {
		var fullImageCarouselObj = $(".js-full-width-image-card");
		$.each(fullImageCarouselObj, function(key, value) {
			var currentImageHeight = $(this).find("img.img-responsive").outerHeight();
			var currentCardHeight = $(this).find(".card.spruce-bar").height();
			if (currentCardHeight > currentImageHeight) {
				var cardCarouselHeight = currentCardHeight;
				$(this).css({"height" : cardCarouselHeight});
			}
		});

    } 
    if(window.innerWidth>768) {
    setTimeout(function(){ adjustFullWidthImageCardHeight(); }, 3000);
    }

function adjustFullWidthImageHeight() {

        var ribbon = $(".ribbon");
        var ribbonHeight = $(ribbon).height();
        var leadercard = $(".card").outerHeight();
    	if ($(".card-event").hasClass('full-width-pos-bot-right')  || $(".card-event").hasClass('full-width-pos-bot-left')){ 
        var cardPosition = $(".card-event").position();
        console.log(cardPosition.top);
        var ribbonCardHeight = (ribbonHeight + leadercard) - cardPosition.top;
        }
        $(ribbon).parent().parent().css({"height" : ribbonCardHeight + "px" });

}
adjustFullWidthImageHeight();

});

$(window).load(function() {
    $(".panel-heading").on("click", function(){
        var currentBoolean = $(this).next().is(':hidden');
        var accordion = $(".panel-heading");
        // Resetting all accordion to collapse state
        $.each(accordion, function(key, value) {
            $(this).next().hide();
            $(this).find(".accordion-toggle").addClass("collapsed");
        });
        if (currentBoolean) {
            $(this).next().show();
            $(this).find(".accordion-toggle").removeClass("collapsed");
        } else {
            $(this).next().hide();
            $(this).find(".accordion-toggle").addClass("collapsed");
        }
    });
});
$( document ).ready(function() {

$( ".digital-enabler-height:eq( 1 )" ).css( "margin-left", "110px" );
$( ".digital-enabler-height:eq( 3 )" ).css( "margin-left", "110px" );

});

function grievanceRecaptchaCallback(){
    var recaptchaWidgetID = grecaptcha.getResponse(window.grievanceWidgetId);
    if(recaptchaWidgetID.length == 0){
        $("#grievance_captcha_error").addClass("captchaError");
        document.getElementById('grievance_captcha_error').style.display='block';
        return false;
    } else {
        $("#grievance_captcha_error").removeClass("captchaError");
        document.getElementById('grievance_captcha_error').style.display='none';
        return true;
    }
}

$(window).load(function() {
    var customerNameLabel = $("#customerNameLabel").text();
    var organizationLabel = $("#organizationLabel").text();
    var descriptionLabel = $("#descriptionLabel").text();
    var evidenceLabel = $("#evidenceLabel").text();
    var emailLabel = $("#contact_Email").text();
    var mobileLabel = $("#contact_Mobile").text();
    var spinner = $('#loader');

    $.validator.addMethod("regex", function(value, element, regexp) {
        if (regexp && regexp.constructor != RegExp) {
            regexp = new RegExp(regexp);
        } else if (regexp.global) regexp.lastIndex = 0;
            return this.optional(element) || regexp.test(value);
        }
    );

    $.validator.addMethod("fileTypeValidation", function(value, element, enableValidation) {
        if(enableValidation) {
            const inputFile = document.getElementById("grievanceFileUpload");
            const fileList = inputFile.files;
            const numFiles = fileList.length;
            let totalFileSize = 0;
            const fileTypes = ['application/pdf','image/jpg', 'image/jpeg', 'image/png'];
            for (let i = 0; i < numFiles; i++) {
                if(fileTypes. indexOf(fileList[i].type) == -1) {
					return false;
                }
            }
        }
        return true;
    });

    $.validator.addMethod("fileCountValidation", function(value, element, enableValidation) {
        if(enableValidation) {
            const inputFile = document.getElementById("grievanceFileUpload");
            const fileList = inputFile.files;
  			if(fileList.length > 10) {
                return false;
            }
        }
        return true;
    });

    $.validator.addMethod("fileSizeValidation", function(value, element, enableValidation) {
        if(enableValidation) {
            const inputFile = document.getElementById("grievanceFileUpload");
            const fileList = inputFile.files;
            let totalFileSize = 0;
            for (let i = 0; i < fileList.length; i++) {
                totalFileSize += fileList[i].size;
            }
            //4194304bytes -> 4MB
            if(totalFileSize > 4194304) {
                return false;
            }
        }
        return true;
    });

    $("#grivance").on('submit', function(event) {
        	event.preventDefault();
        	return false;
        }).validate({
        rules: {
            name: {
                required: false
            },
            email: {
                required: false,
                email: true,
                regex: /^\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i
            },
            mobile: {
                required: false,
                digits: true,
                minlength: 10,
                maxlength: 15
            },
            description: {
                required: true,
                minlength: 4,
                maxlength: 200
            },
            checkbox: {
                required: true
            },
            file: {
                required: false,
                fileTypeValidation: true,
                fileCountValidation: true,
                fileSizeValidation: true
            }
        },

        messages: {
            name: {
                required: "Please enter your name",
            },
            mobile: {
                required: "This field is optional",
                minlength: "Your mobile number must be at least 10 characters long"
            },
            description: {
                required: "Please provide description",
                minlength: "Your description must be at least 4 characters long"

            },
            email: {
                required: "Please enter your email address",
                email: "Enter valid email address",
                regex: "Enter valid email address"
            },
            checkbox: {
                required: "Please agree to the privacy policy to proceed"
            },
            file: {
                required: "This field is optional",
                fileTypeValidation: "Accepted file types are 'application/pdf', 'image/jpg', 'image/jpeg', 'image/png'",
                fileCountValidation: "Maximum of 10 files allowed",
                fileSizeValidation: "Total files size should be less than 4MB"
            }
        },
        highlight: function (element) {
            $(element).addClass('error').removeClass('valid');
            },
        unhighlight: function (element) {
            if ($(element).val().trim().length == 0) {
                $(element).removeClass("valid");
            }
            else {
                $(element).addClass('valid').removeClass('error');
            }
			var email = $('input.form-control#email').val();
            var mobile = $('input.form-control#mobile').val();
            if ($(element).attr('id')=='email' && jQuery.trim(email).length < 1)
                return;
            if ($(element).attr('id')=='mobile' && jQuery.trim(mobile).length < 1)
                return;
            },
            
        invalidHandler: function(form, validator) {
            grievanceRecaptchaCallback();                   
        },
        submitHandler: function(form) {
            spinner.show();
            const recaptcha = grievanceRecaptchaCallback();
            let formData = new FormData($("#grivance")[0]);
            let grievanceFormApiUrl =  $("#grivance").attr("data-grievance-form-api-url");
            if(recaptcha) {
                $.ajax({
                    url: grievanceFormApiUrl,
                    type: "POST",
                    data: formData,
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function(response) {
                        swal(
                            "Thank you for submitting a grievance.",
                            "We will acknowledge your grievance within 1 week."
                        )
                        $("#grivance")[0].reset();
                        grecaptcha.reset(window.grievanceWidgetId);
                        $('div.form-group input, div.form-group textarea').removeClass("valid error");
                        spinner.hide();
                    },
    
                    error: function(response) {
                        swal(
                            "Internal Error",
                            "The form could not be submitted. Please try again in some time",
                            "error"
                        )
                        $("#grivance")[0].reset();
                        grecaptcha.reset(window.grievanceWidgetId);
                        $('div.form-group input, div.form-group textarea').removeClass("valid error");
                        spinner.hide();
                    }
                });
            }
        },
    });
});
/*
     _ _      _       _
 ___| (_) ___| | __  (_)___
/ __| | |/ __| |/ /  | / __|
\__ \ | | (__|   < _ | \__ \
|___/_|_|\___|_|\_(_)/ |___/
                   |__/

 Version: 1.8.1
  Author: Ken Wheeler
 Website: http://kenwheeler.github.io
    Docs: http://kenwheeler.github.io/slick
    Repo: http://github.com/kenwheeler/slick
  Issues: http://github.com/kenwheeler/slick/issues

 */
/* global window, document, define, jQuery, setInterval, clearInterval */


;(function(factory) {
    'use strict';
    if (typeof define === 'function' && define.amd) {
        define(['jquery'], factory);
    } else if (typeof exports !== 'undefined') {
        module.exports = factory(require('jquery'));
    } else {
        factory(jQuery);
    }

}(function($) {
    'use strict';
    var Slick = window.Slick || {};

    Slick = (function() {

        var instanceUid = 0;

        function Slick(element, settings) {

            var _ = this, dataSettings;

            _.defaults = {
                accessibility: true,
                adaptiveHeight: false,
                appendArrows: $(element),
                appendDots: $(element),
                arrows: true,
                asNavFor: null,
                prevArrow: '<button class="slick-prev" aria-label="Previous" type="button">Previous</button>',
                nextArrow: '<button class="slick-next" aria-label="Next" type="button">Next</button>',
                autoplay: window.autoplay ? true : false,
                autoplaySpeed: 4000,
                centerMode: false,
                centerPadding: '50px',
                cssEase: 'ease',
                customPaging: function(slider, i) {
                    return $('<button type="button" />').text(i + 1);
                },
                dots: false,
                dotsClass: 'slick-dots',
                draggable: true,
                easing: 'linear',
                edgeFriction: 0.35,
                fade: false,
                focusOnSelect: false,
                focusOnChange: false,
                infinite: true,
                initialSlide: 0,
                lazyLoad: 'ondemand',
                mobileFirst: false,
                pauseOnHover: true,
                pauseOnFocus: false,
                pauseOnDotsHover: false,
                respondTo: 'window',
                responsive: null,
                rows: 1,
                rtl: false,
                slide: '',
                slidesPerRow: 1,
                slidesToShow: 1,
                slidesToScroll: 1,
                speed: 500,
                swipe: true,
                swipeToSlide: false,
                touchMove: true,
                touchThreshold: 5,
                useCSS: true,
                useTransform: true,
                variableWidth: false,
                vertical: false,
                verticalSwiping: false,
                waitForAnimate: true,
                zIndex: 1000
            };

            _.initials = {
                animating: false,
                dragging: false,
                autoPlayTimer: null,
                currentDirection: 0,
                currentLeft: null,
                currentSlide: 0,
                direction: 1,
                $dots: null,
                listWidth: null,
                listHeight: null,
                loadIndex: 0,
                $nextArrow: null,
                $prevArrow: null,
                scrolling: false,
                slideCount: null,
                slideWidth: null,
                $slideTrack: null,
                $slides: null,
                sliding: false,
                slideOffset: 0,
                swipeLeft: null,
                swiping: false,
                $list: null,
                touchObject: {},
                transformsEnabled: false,
                unslicked: false
            };

            $.extend(_, _.initials);

            _.activeBreakpoint = null;
            _.animType = null;
            _.animProp = null;
            _.breakpoints = [];
            _.breakpointSettings = [];
            _.cssTransitions = false;
            _.focussed = false;
            _.interrupted = false;
            _.hidden = 'hidden';
            _.paused = true;
            _.positionProp = null;
            _.respondTo = null;
            _.rowCount = 1;
            _.shouldClick = true;
            _.$slider = $(element);
            _.$slidesCache = null;
            _.transformType = null;
            _.transitionType = null;
            _.visibilityChange = 'visibilitychange';
            _.windowWidth = 0;
            _.windowTimer = null;

            dataSettings = $(element).data('slick') || {};

            _.options = $.extend({}, _.defaults, settings, dataSettings);

            _.currentSlide = _.options.initialSlide;

            _.originalSettings = _.options;

            if (typeof document.mozHidden !== 'undefined') {
                _.hidden = 'mozHidden';
                _.visibilityChange = 'mozvisibilitychange';
            } else if (typeof document.webkitHidden !== 'undefined') {
                _.hidden = 'webkitHidden';
                _.visibilityChange = 'webkitvisibilitychange';
            }

            _.autoPlay = $.proxy(_.autoPlay, _);
            _.autoPlayClear = $.proxy(_.autoPlayClear, _);
            _.autoPlayIterator = $.proxy(_.autoPlayIterator, _);
            _.changeSlide = $.proxy(_.changeSlide, _);
            _.clickHandler = $.proxy(_.clickHandler, _);
            _.selectHandler = $.proxy(_.selectHandler, _);
            _.setPosition = $.proxy(_.setPosition, _);
            _.swipeHandler = $.proxy(_.swipeHandler, _);
            _.dragHandler = $.proxy(_.dragHandler, _);
            _.keyHandler = $.proxy(_.keyHandler, _);

            _.instanceUid = instanceUid++;

            // A simple way to check for HTML strings
            // Strict HTML recognition (must start with <)
            // Extracted from jQuery v1.11 source
            _.htmlExpr = /^(?:\s*(<[\w\W]+>)[^>]*)$/;


            _.registerBreakpoints();
            _.init(true);

        }

        return Slick;

    }());

    Slick.prototype.activateADA = function() {
        var _ = this;

        _.$slideTrack.find('.slick-active').attr({
            'aria-hidden': 'false'
        }).find('a, input, button, select').attr({
            'tabindex': '0'
        });

    };

    Slick.prototype.addSlide = Slick.prototype.slickAdd = function(markup, index, addBefore) {

        var _ = this;

        if (typeof(index) === 'boolean') {
            addBefore = index;
            index = null;
        } else if (index < 0 || (index >= _.slideCount)) {
            return false;
        }

        _.unload();

        if (typeof(index) === 'number') {
            if (index === 0 && _.$slides.length === 0) {
                $(markup).appendTo(_.$slideTrack);
            } else if (addBefore) {
                $(markup).insertBefore(_.$slides.eq(index));
            } else {
                $(markup).insertAfter(_.$slides.eq(index));
            }
        } else {
            if (addBefore === true) {
                $(markup).prependTo(_.$slideTrack);
            } else {
                $(markup).appendTo(_.$slideTrack);
            }
        }

        _.$slides = _.$slideTrack.children(this.options.slide);

        _.$slideTrack.children(this.options.slide).detach();

        _.$slideTrack.append(_.$slides);

        _.$slides.each(function(index, element) {
            $(element).attr('data-slick-index', index);
        });

        _.$slidesCache = _.$slides;

        _.reinit();

    };

    Slick.prototype.animateHeight = function() {
        var _ = this;
        if (_.options.slidesToShow === 1 && _.options.adaptiveHeight === true && _.options.vertical === false) {
            var targetHeight = _.$slides.eq(_.currentSlide).outerHeight(true);
            _.$list.animate({
                height: targetHeight
            }, _.options.speed);
        }
    };

    Slick.prototype.animateSlide = function(targetLeft, callback) {

        var animProps = {},
            _ = this;

        _.animateHeight();

        if (_.options.rtl === true && _.options.vertical === false) {
            targetLeft = -targetLeft;
        }
        if (_.transformsEnabled === false) {
            if (_.options.vertical === false) {
                _.$slideTrack.animate({
                    left: targetLeft
                }, _.options.speed, _.options.easing, callback);
            } else {
                _.$slideTrack.animate({
                    top: targetLeft
                }, _.options.speed, _.options.easing, callback);
            }

        } else {

            if (_.cssTransitions === false) {
                if (_.options.rtl === true) {
                    _.currentLeft = -(_.currentLeft);
                }
                $({
                    animStart: _.currentLeft
                }).animate({
                    animStart: targetLeft
                }, {
                    duration: _.options.speed,
                    easing: _.options.easing,
                    step: function(now) {
                        now = Math.ceil(now);
                        if (_.options.vertical === false) {
                            animProps[_.animType] = 'translate(' +
                                now + 'px, 0px)';
                            _.$slideTrack.css(animProps);
                        } else {
                            animProps[_.animType] = 'translate(0px,' +
                                now + 'px)';
                            _.$slideTrack.css(animProps);
                        }
                    },
                    complete: function() {
                        if (callback) {
                            callback.call();
                        }
                    }
                });

            } else {

                _.applyTransition();
                targetLeft = Math.ceil(targetLeft);

                if (_.options.vertical === false) {
                    animProps[_.animType] = 'translate3d(' + targetLeft + 'px, 0px, 0px)';
                } else {
                    animProps[_.animType] = 'translate3d(0px,' + targetLeft + 'px, 0px)';
                }
                _.$slideTrack.css(animProps);

                if (callback) {
                    setTimeout(function() {

                        _.disableTransition();

                        callback.call();
                    }, _.options.speed);
                }

            }

        }

    };

    Slick.prototype.getNavTarget = function() {

        var _ = this,
            asNavFor = _.options.asNavFor;

        if ( asNavFor && asNavFor !== null ) {
            asNavFor = $(asNavFor).not(_.$slider);
        }

        return asNavFor;

    };

    Slick.prototype.asNavFor = function(index) {

        var _ = this,
            asNavFor = _.getNavTarget();

        if ( asNavFor !== null && typeof asNavFor === 'object' ) {
            asNavFor.each(function() {
                var target = $(this).slick('getSlick');
                if(!target.unslicked) {
                    target.slideHandler(index, true);
                }
            });
        }

    };

    Slick.prototype.applyTransition = function(slide) {

        var _ = this,
            transition = {};

        if (_.options.fade === false) {
            transition[_.transitionType] = _.transformType + ' ' + _.options.speed + 'ms ' + _.options.cssEase;
        } else {
            transition[_.transitionType] = 'opacity ' + _.options.speed + 'ms ' + _.options.cssEase;
        }

        if (_.options.fade === false) {
            _.$slideTrack.css(transition);
        } else {
            _.$slides.eq(slide).css(transition);
        }

    };

    Slick.prototype.autoPlay = function() {

        var _ = this;

        _.autoPlayClear();

        if ( _.slideCount > _.options.slidesToShow ) {
            _.autoPlayTimer = setInterval( _.autoPlayIterator, _.options.autoplaySpeed );
        }

    };

    Slick.prototype.autoPlayClear = function() {

        var _ = this;

        if (_.autoPlayTimer) {
            clearInterval(_.autoPlayTimer);
        }

    };

    Slick.prototype.autoPlayIterator = function() {

        var _ = this,
            slideTo = _.currentSlide + _.options.slidesToScroll;

        if ( !_.paused && !_.interrupted && !_.focussed ) {

            if ( _.options.infinite === false ) {

                if ( _.direction === 1 && ( _.currentSlide + 1 ) === ( _.slideCount - 1 )) {
                    _.direction = 0;
                }

                else if ( _.direction === 0 ) {

                    slideTo = _.currentSlide - _.options.slidesToScroll;

                    if ( _.currentSlide - 1 === 0 ) {
                        _.direction = 1;
                    }

                }

            }

            _.slideHandler( slideTo );

        }

    };

    Slick.prototype.buildArrows = function() {

        var _ = this;

        if (_.options.arrows === true ) {

            _.$prevArrow = $(_.options.prevArrow).addClass('slick-arrow');
            _.$nextArrow = $(_.options.nextArrow).addClass('slick-arrow');

            if( _.slideCount > _.options.slidesToShow ) {

                _.$prevArrow.removeClass('slick-hidden').removeAttr('aria-hidden tabindex');
                _.$nextArrow.removeClass('slick-hidden').removeAttr('aria-hidden tabindex');

                if (_.htmlExpr.test(_.options.prevArrow)) {
                    _.$prevArrow.prependTo(_.options.appendArrows);
                }

                if (_.htmlExpr.test(_.options.nextArrow)) {
                    _.$nextArrow.appendTo(_.options.appendArrows);
                }

                if (_.options.infinite !== true) {
                    _.$prevArrow
                        .addClass('slick-disabled')
                        .attr('aria-disabled', 'true');
                }

            } else {

                _.$prevArrow.add( _.$nextArrow )

                    .addClass('slick-hidden')
                    .attr({
                        'aria-disabled': 'true',
                        'tabindex': '-1'
                    });

            }

        }

    };

    Slick.prototype.buildDots = function() {

        var _ = this,
            i, dot;

        if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {

            _.$slider.addClass('slick-dotted');

            dot = $('<ul />').addClass(_.options.dotsClass);

            for (i = 0; i <= _.getDotCount(); i += 1) {
                dot.append($('<li />').append(_.options.customPaging.call(this, _, i)));
            }

            _.$dots = dot.appendTo(_.options.appendDots);

            _.$dots.find('li').first().addClass('slick-active');

        }

    };

    Slick.prototype.buildOut = function() {

        var _ = this;

        _.$slides =
            _.$slider
                .children( _.options.slide + ':not(.slick-cloned)')
                .addClass('slick-slide');

        _.slideCount = _.$slides.length;

        _.$slides.each(function(index, element) {
            $(element)
                .attr('data-slick-index', index)
                .data('originalStyling', $(element).attr('style') || '');
        });

        _.$slider.addClass('slick-slider');

        _.$slideTrack = (_.slideCount === 0) ?
            $('<div class="slick-track"/>').appendTo(_.$slider) :
            _.$slides.wrapAll('<div class="slick-track"/>').parent();

        _.$list = _.$slideTrack.wrap(
            '<div class="slick-list"/>').parent();
        _.$slideTrack.css('opacity', 0);

        if (_.options.centerMode === true || _.options.swipeToSlide === true) {
            _.options.slidesToScroll = 1;
        }

        $('img[data-lazy]', _.$slider).not('[src]').addClass('slick-loading');

        _.setupInfinite();

        _.buildArrows();

        _.buildDots();

        _.updateDots();


        _.setSlideClasses(typeof _.currentSlide === 'number' ? _.currentSlide : 0);

        if (_.options.draggable === true) {
            _.$list.addClass('draggable');
        }

    };

    Slick.prototype.buildRows = function() {

        var _ = this, a, b, c, newSlides, numOfSlides, originalSlides,slidesPerSection;

        newSlides = document.createDocumentFragment();
        originalSlides = _.$slider.children();

        if(_.options.rows > 0) {

            slidesPerSection = _.options.slidesPerRow * _.options.rows;
            numOfSlides = Math.ceil(
                originalSlides.length / slidesPerSection
            );

            for(a = 0; a < numOfSlides; a++){
                var slide = document.createElement('div');
                for(b = 0; b < _.options.rows; b++) {
                    var row = document.createElement('div');
                    for(c = 0; c < _.options.slidesPerRow; c++) {
                        var target = (a * slidesPerSection + ((b * _.options.slidesPerRow) + c));
                        if (originalSlides.get(target)) {
                            row.appendChild(originalSlides.get(target));
                        }
                    }
                    slide.appendChild(row);
                }
                newSlides.appendChild(slide);
            }

            _.$slider.empty().append(newSlides);
            _.$slider.children().children().children()
                .css({
                    'width':(100 / _.options.slidesPerRow) + '%',
                    'display': 'inline-block'
                });

        }

    };

    Slick.prototype.checkResponsive = function(initial, forceUpdate) {

        var _ = this,
            breakpoint, targetBreakpoint, respondToWidth, triggerBreakpoint = false;
        var sliderWidth = _.$slider.width();
        var windowWidth = window.innerWidth || $(window).width();

        if (_.respondTo === 'window') {
            respondToWidth = windowWidth;
        } else if (_.respondTo === 'slider') {
            respondToWidth = sliderWidth;
        } else if (_.respondTo === 'min') {
            respondToWidth = Math.min(windowWidth, sliderWidth);
        }

        if ( _.options.responsive &&
            _.options.responsive.length &&
            _.options.responsive !== null) {

            targetBreakpoint = null;

            for (breakpoint in _.breakpoints) {
                if (_.breakpoints.hasOwnProperty(breakpoint)) {
                    if (_.originalSettings.mobileFirst === false) {
                        if (respondToWidth < _.breakpoints[breakpoint]) {
                            targetBreakpoint = _.breakpoints[breakpoint];
                        }
                    } else {
                        if (respondToWidth > _.breakpoints[breakpoint]) {
                            targetBreakpoint = _.breakpoints[breakpoint];
                        }
                    }
                }
            }

            if (targetBreakpoint !== null) {
                if (_.activeBreakpoint !== null) {
                    if (targetBreakpoint !== _.activeBreakpoint || forceUpdate) {
                        _.activeBreakpoint =
                            targetBreakpoint;
                        if (_.breakpointSettings[targetBreakpoint] === 'unslick') {
                            _.unslick(targetBreakpoint);
                        } else {
                            _.options = $.extend({}, _.originalSettings,
                                _.breakpointSettings[
                                    targetBreakpoint]);
                            if (initial === true) {
                                _.currentSlide = _.options.initialSlide;
                            }
                            _.refresh(initial);
                        }
                        triggerBreakpoint = targetBreakpoint;
                    }
                } else {
                    _.activeBreakpoint = targetBreakpoint;
                    if (_.breakpointSettings[targetBreakpoint] === 'unslick') {
                        _.unslick(targetBreakpoint);
                    } else {
                        _.options = $.extend({}, _.originalSettings,
                            _.breakpointSettings[
                                targetBreakpoint]);
                        if (initial === true) {
                            _.currentSlide = _.options.initialSlide;
                        }
                        _.refresh(initial);
                    }
                    triggerBreakpoint = targetBreakpoint;
                }
            } else {
                if (_.activeBreakpoint !== null) {
                    _.activeBreakpoint = null;
                    _.options = _.originalSettings;
                    if (initial === true) {
                        _.currentSlide = _.options.initialSlide;
                    }
                    _.refresh(initial);
                    triggerBreakpoint = targetBreakpoint;
                }
            }

            // only trigger breakpoints during an actual break. not on initialize.
            if( !initial && triggerBreakpoint !== false ) {
                _.$slider.trigger('breakpoint', [_, triggerBreakpoint]);
            }
        }

    };

    Slick.prototype.changeSlide = function(event, dontAnimate) {

        var _ = this,
            $target = $(event.currentTarget),
            indexOffset, slideOffset, unevenOffset;

        // If target is a link, prevent default action.
        if($target.is('a')) {
            event.preventDefault();
        }

        // If target is not the <li> element (ie: a child), find the <li>.
        if(!$target.is('li')) {
            $target = $target.closest('li');
        }

        unevenOffset = (_.slideCount % _.options.slidesToScroll !== 0);
        indexOffset = unevenOffset ? 0 : (_.slideCount - _.currentSlide) % _.options.slidesToScroll;

        switch (event.data.message) {

            case 'previous':
                slideOffset = indexOffset === 0 ? _.options.slidesToScroll : _.options.slidesToShow - indexOffset;
                if (_.slideCount > _.options.slidesToShow) {
                    _.slideHandler(_.currentSlide - slideOffset, false, dontAnimate);
                }
                break;

            case 'next':
                slideOffset = indexOffset === 0 ? _.options.slidesToScroll : indexOffset;
                if (_.slideCount > _.options.slidesToShow) {
                    _.slideHandler(_.currentSlide + slideOffset, false, dontAnimate);
                }
                break;

            case 'index':
                var index = event.data.index === 0 ? 0 :
                    event.data.index || $target.index() * _.options.slidesToScroll;

                _.slideHandler(_.checkNavigable(index), false, dontAnimate);
                $target.children().trigger('focus');
                break;

            default:
                return;
        }

    };

    Slick.prototype.checkNavigable = function(index) {

        var _ = this,
            navigables, prevNavigable;

        navigables = _.getNavigableIndexes();
        prevNavigable = 0;
        if (index > navigables[navigables.length - 1]) {
            index = navigables[navigables.length - 1];
        } else {
            for (var n in navigables) {
                if (index < navigables[n]) {
                    index = prevNavigable;
                    break;
                }
                prevNavigable = navigables[n];
            }
        }

        return index;
    };

    Slick.prototype.cleanUpEvents = function() {

        var _ = this;

        if (_.options.dots && _.$dots !== null) {

            $('li', _.$dots)
                .off('click.slick', _.changeSlide)
                .off('mouseenter.slick', $.proxy(_.interrupt, _, true))
                .off('mouseleave.slick', $.proxy(_.interrupt, _, false));

            if (_.options.accessibility === true) {
                _.$dots.off('keydown.slick', _.keyHandler);
            }
        }

        _.$slider.off('focus.slick blur.slick');

        if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {
            _.$prevArrow && _.$prevArrow.off('click.slick', _.changeSlide);
            _.$nextArrow && _.$nextArrow.off('click.slick', _.changeSlide);

            if (_.options.accessibility === true) {
                _.$prevArrow && _.$prevArrow.off('keydown.slick', _.keyHandler);
                _.$nextArrow && _.$nextArrow.off('keydown.slick', _.keyHandler);
            }
        }

        _.$list.off('touchstart.slick mousedown.slick', _.swipeHandler);
        _.$list.off('touchmove.slick mousemove.slick', _.swipeHandler);
        _.$list.off('touchend.slick mouseup.slick', _.swipeHandler);
        _.$list.off('touchcancel.slick mouseleave.slick', _.swipeHandler);

        _.$list.off('click.slick', _.clickHandler);

        $(document).off(_.visibilityChange, _.visibility);

        _.cleanUpSlideEvents();

        if (_.options.accessibility === true) {
            _.$list.off('keydown.slick', _.keyHandler);
        }

        if (_.options.focusOnSelect === true) {
            $(_.$slideTrack).children().off('click.slick', _.selectHandler);
        }

        $(window).off('orientationchange.slick.slick-' + _.instanceUid, _.orientationChange);

        $(window).off('resize.slick.slick-' + _.instanceUid, _.resize);

        $('[draggable!=true]', _.$slideTrack).off('dragstart', _.preventDefault);

        $(window).off('load.slick.slick-' + _.instanceUid, _.setPosition);

    };

    Slick.prototype.cleanUpSlideEvents = function() {

        var _ = this;

        _.$list.off('mouseenter.slick', $.proxy(_.interrupt, _, true));
        _.$list.off('mouseleave.slick', $.proxy(_.interrupt, _, false));

    };

    Slick.prototype.cleanUpRows = function() {

        var _ = this, originalSlides;

        if(_.options.rows > 0) {
            originalSlides = _.$slides.children().children();
            originalSlides.removeAttr('style');
            _.$slider.empty().append(originalSlides);
        }

    };

    Slick.prototype.clickHandler = function(event) {

        var _ = this;

        if (_.shouldClick === false) {
            event.stopImmediatePropagation();
            event.stopPropagation();
            event.preventDefault();
        }

    };

    Slick.prototype.destroy = function(refresh) {

        var _ = this;

        _.autoPlayClear();

        _.touchObject = {};

        _.cleanUpEvents();

        $('.slick-cloned', _.$slider).detach();

        if (_.$dots) {
            _.$dots.remove();
        }

        if ( _.$prevArrow && _.$prevArrow.length ) {

            _.$prevArrow
                .removeClass('slick-disabled slick-arrow slick-hidden')
                .removeAttr('aria-hidden aria-disabled tabindex')
                .css('display','');

            if ( _.htmlExpr.test( _.options.prevArrow )) {
                _.$prevArrow.remove();
            }
        }

        if ( _.$nextArrow && _.$nextArrow.length ) {

            _.$nextArrow
                .removeClass('slick-disabled slick-arrow slick-hidden')
                .removeAttr('aria-hidden aria-disabled tabindex')
                .css('display','');

            if ( _.htmlExpr.test( _.options.nextArrow )) {
                _.$nextArrow.remove();
            }
        }


        if (_.$slides) {

            _.$slides
                .removeClass('slick-slide slick-active slick-center slick-visible slick-current')
                .removeAttr('aria-hidden')
                .removeAttr('data-slick-index')
                .each(function(){
                    $(this).attr('style', $(this).data('originalStyling'));
                });

            _.$slideTrack.children(this.options.slide).detach();

            _.$slideTrack.detach();

            _.$list.detach();

            _.$slider.append(_.$slides);
        }

        _.cleanUpRows();

        _.$slider.removeClass('slick-slider');
        _.$slider.removeClass('slick-initialized');
        _.$slider.removeClass('slick-dotted');

        _.unslicked = true;

        if(!refresh) {
            _.$slider.trigger('destroy', [_]);
        }

    };

    Slick.prototype.disableTransition = function(slide) {

        var _ = this,
            transition = {};

        transition[_.transitionType] = '';

        if (_.options.fade === false) {
            _.$slideTrack.css(transition);
        } else {
            _.$slides.eq(slide).css(transition);
        }

    };

    Slick.prototype.fadeSlide = function(slideIndex, callback) {

        var _ = this;

        if (_.cssTransitions === false) {

            _.$slides.eq(slideIndex).css({
                zIndex: _.options.zIndex
            });

            _.$slides.eq(slideIndex).animate({
                opacity: 1
            }, _.options.speed, _.options.easing, callback);

        } else {

            _.applyTransition(slideIndex);

            _.$slides.eq(slideIndex).css({
                opacity: 1,
                zIndex: _.options.zIndex
            });

            if (callback) {
                setTimeout(function() {

                    _.disableTransition(slideIndex);

                    callback.call();
                }, _.options.speed);
            }

        }

    };

    Slick.prototype.fadeSlideOut = function(slideIndex) {

        var _ = this;

        if (_.cssTransitions === false) {

            _.$slides.eq(slideIndex).animate({
                opacity: 0,
                zIndex: _.options.zIndex - 2
            }, _.options.speed, _.options.easing);

        } else {

            _.applyTransition(slideIndex);

            _.$slides.eq(slideIndex).css({
                opacity: 0,
                zIndex: _.options.zIndex - 2
            });

        }

    };

    Slick.prototype.filterSlides = Slick.prototype.slickFilter = function(filter) {

        var _ = this;

        if (filter !== null) {

            _.$slidesCache = _.$slides;

            _.unload();

            _.$slideTrack.children(this.options.slide).detach();

            _.$slidesCache.filter(filter).appendTo(_.$slideTrack);

            _.reinit();

        }

    };

    Slick.prototype.focusHandler = function() {

        var _ = this;

        _.$slider
            .off('focus.slick blur.slick')
            .on('focus.slick blur.slick', '*', function(event) {

            event.stopImmediatePropagation();
            var $sf = $(this);

            setTimeout(function() {

                if( _.options.pauseOnFocus ) {
                    _.focussed = $sf.is(':focus');
                    _.autoPlay();
                }

            }, 0);

        });
    };

    Slick.prototype.getCurrent = Slick.prototype.slickCurrentSlide = function() {

        var _ = this;
        return _.currentSlide;

    };

    Slick.prototype.getDotCount = function() {

        var _ = this;

        var breakPoint = 0;
        var counter = 0;
        var pagerQty = 0;

        if (_.options.infinite === true) {
            if (_.slideCount <= _.options.slidesToShow) {
                 ++pagerQty;
            } else {
                while (breakPoint < _.slideCount) {
                    ++pagerQty;
                    breakPoint = counter + _.options.slidesToScroll;
                    counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow;
                }
            }
        } else if (_.options.centerMode === true) {
            pagerQty = _.slideCount;
        } else if(!_.options.asNavFor) {
            pagerQty = 1 + Math.ceil((_.slideCount - _.options.slidesToShow) / _.options.slidesToScroll);
        }else {
            while (breakPoint < _.slideCount) {
                ++pagerQty;
                breakPoint = counter + _.options.slidesToScroll;
                counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow;
            }
        }

        return pagerQty - 1;

    };

    Slick.prototype.getLeft = function(slideIndex) {

        var _ = this,
            targetLeft,
            verticalHeight,
            verticalOffset = 0,
            targetSlide,
            coef;

        _.slideOffset = 0;
        verticalHeight = _.$slides.first().outerHeight(true);

        if (_.options.infinite === true) {
            if (_.slideCount > _.options.slidesToShow) {
                _.slideOffset = (_.slideWidth * _.options.slidesToShow) * -1;
                coef = -1

                if (_.options.vertical === true && _.options.centerMode === true) {
                    if (_.options.slidesToShow === 2) {
                        coef = -1.5;
                    } else if (_.options.slidesToShow === 1) {
                        coef = -2
                    }
                }
                verticalOffset = (verticalHeight * _.options.slidesToShow) * coef;
            }
            if (_.slideCount % _.options.slidesToScroll !== 0) {
                if (slideIndex + _.options.slidesToScroll > _.slideCount && _.slideCount > _.options.slidesToShow) {
                    if (slideIndex > _.slideCount) {
                        _.slideOffset = ((_.options.slidesToShow - (slideIndex - _.slideCount)) * _.slideWidth) * -1;
                        verticalOffset = ((_.options.slidesToShow - (slideIndex - _.slideCount)) * verticalHeight) * -1;
                    } else {
                        _.slideOffset = ((_.slideCount % _.options.slidesToScroll) * _.slideWidth) * -1;
                        verticalOffset = ((_.slideCount % _.options.slidesToScroll) * verticalHeight) * -1;
                    }
                }
            }
        } else {
            if (slideIndex + _.options.slidesToShow > _.slideCount) {
                _.slideOffset = ((slideIndex + _.options.slidesToShow) - _.slideCount) * _.slideWidth;
                verticalOffset = ((slideIndex + _.options.slidesToShow) - _.slideCount) * verticalHeight;
            }
        }

        if (_.slideCount <= _.options.slidesToShow) {
            _.slideOffset = 0;
            verticalOffset = 0;
        }

        if (_.options.centerMode === true && _.slideCount <= _.options.slidesToShow) {
            _.slideOffset = ((_.slideWidth * Math.floor(_.options.slidesToShow)) / 2) - ((_.slideWidth * _.slideCount) / 2);
        } else if (_.options.centerMode === true && _.options.infinite === true) {
            _.slideOffset += _.slideWidth * Math.floor(_.options.slidesToShow / 2) - _.slideWidth;
        } else if (_.options.centerMode === true) {
            _.slideOffset = 0;
            _.slideOffset += _.slideWidth * Math.floor(_.options.slidesToShow / 2);
        }

        if (_.options.vertical === false) {
            targetLeft = ((slideIndex * _.slideWidth) * -1) + _.slideOffset;
        } else {
            targetLeft = ((slideIndex * verticalHeight) * -1) + verticalOffset;
        }

        if (_.options.variableWidth === true) {

            if (_.slideCount <= _.options.slidesToShow || _.options.infinite === false) {
                targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex);
            } else {
                targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex + _.options.slidesToShow);
            }

            if (_.options.rtl === true) {
                if (targetSlide[0]) {
                    targetLeft = (_.$slideTrack.width() - targetSlide[0].offsetLeft - targetSlide.width()) * -1;
                } else {
                    targetLeft =  0;
                }
            } else {
                targetLeft = targetSlide[0] ? targetSlide[0].offsetLeft * -1 : 0;
            }

            if (_.options.centerMode === true) {
                if (_.slideCount <= _.options.slidesToShow || _.options.infinite === false) {
                    targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex);
                } else {
                    targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex + _.options.slidesToShow + 1);
                }

                if (_.options.rtl === true) {
                    if (targetSlide[0]) {
                        targetLeft = (_.$slideTrack.width() - targetSlide[0].offsetLeft - targetSlide.width()) * -1;
                    } else {
                        targetLeft =  0;
                    }
                } else {
                    targetLeft = targetSlide[0] ? targetSlide[0].offsetLeft * -1 : 0;
                }

                targetLeft += (_.$list.width() - targetSlide.outerWidth()) / 2;
            }
        }

        return targetLeft;

    };

    Slick.prototype.getOption = Slick.prototype.slickGetOption = function(option) {

        var _ = this;

        return _.options[option];

    };

    Slick.prototype.getNavigableIndexes = function() {

        var _ = this,
            breakPoint = 0,
            counter = 0,
            indexes = [],
            max;

        if (_.options.infinite === false) {
            max = _.slideCount;
        } else {
            breakPoint = _.options.slidesToScroll * -1;
            counter = _.options.slidesToScroll * -1;
            max = _.slideCount * 2;
        }

        while (breakPoint < max) {
            indexes.push(breakPoint);
            breakPoint = counter + _.options.slidesToScroll;
            counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow;
        }

        return indexes;

    };

    Slick.prototype.getSlick = function() {

        return this;

    };

    Slick.prototype.getSlideCount = function() {

        var _ = this,
            slidesTraversed, swipedSlide, centerOffset;

        centerOffset = _.options.centerMode === true ? _.slideWidth * Math.floor(_.options.slidesToShow / 2) : 0;

        if (_.options.swipeToSlide === true) {
            _.$slideTrack.find('.slick-slide').each(function(index, slide) {
                if (slide.offsetLeft - centerOffset + ($(slide).outerWidth() / 2) > (_.swipeLeft * -1)) {
                    swipedSlide = slide;
                    return false;
                }
            });

            slidesTraversed = Math.abs($(swipedSlide).attr('data-slick-index') - _.currentSlide) || 1;

            return slidesTraversed;

        } else {
            return _.options.slidesToScroll;
        }

    };

    Slick.prototype.goTo = Slick.prototype.slickGoTo = function(slide, dontAnimate) {

        var _ = this;

        _.changeSlide({
            data: {
                message: 'index',
                index: parseInt(slide)
            }
        }, dontAnimate);

    };

    Slick.prototype.init = function(creation) {

        var _ = this;

        if (!$(_.$slider).hasClass('slick-initialized')) {

            $(_.$slider).addClass('slick-initialized');

            _.buildRows();
            _.buildOut();
            _.setProps();
            _.startLoad();
            _.loadSlider();
            _.initializeEvents();
            _.updateArrows();
            _.updateDots();
            _.checkResponsive(true);
            _.focusHandler();

        }

        if (creation) {
            _.$slider.trigger('init', [_]);
        }

        if (_.options.accessibility === true) {
            _.initADA();
        }

        if ( _.options.autoplay ) {

            _.paused = false;
            _.autoPlay();

        }

    };

    Slick.prototype.initADA = function() {
        var _ = this,
                numDotGroups = Math.ceil(_.slideCount / _.options.slidesToShow),
                tabControlIndexes = _.getNavigableIndexes().filter(function(val) {
                    return (val >= 0) && (val < _.slideCount);
                });

        _.$slides.add(_.$slideTrack.find('.slick-cloned')).attr({
            'aria-hidden': 'true',
            'tabindex': '-1'
        }).find('a, input, button, select').attr({
            'tabindex': '-1'
        });

        if (_.$dots !== null) {
            _.$slides.not(_.$slideTrack.find('.slick-cloned')).each(function(i) {
                var slideControlIndex = tabControlIndexes.indexOf(i);

                $(this).attr({
                    'role': 'tabpanel',
                    'id': 'slick-slide' + _.instanceUid + i,
                    'tabindex': -1
                });

                if (slideControlIndex !== -1) {
                   var ariaButtonControl = 'slick-slide-control' + _.instanceUid + slideControlIndex
                   if ($('#' + ariaButtonControl).length) {
                     $(this).attr({
                         'aria-describedby': ariaButtonControl
                     });
                   }
                }
            });

            _.$dots.attr('role', 'tablist').find('li').each(function(i) {
                var mappedSlideIndex = tabControlIndexes[i];

                $(this).attr({
                    'role': 'presentation'
                });

                $(this).find('button').first().attr({
                    'role': 'tab',
                    'id': 'slick-slide-control' + _.instanceUid + i,
                    'aria-controls': 'slick-slide' + _.instanceUid + mappedSlideIndex,
                    'aria-label': (i + 1) + ' of ' + numDotGroups,
                    'aria-selected': null,
                    'tabindex': '-1'
                });

            }).eq(_.currentSlide).find('button').attr({
                'aria-selected': 'true',
                'tabindex': '0'
            }).end();
        }

        for (var i=_.currentSlide, max=i+_.options.slidesToShow; i < max; i++) {
          if (_.options.focusOnChange) {
            _.$slides.eq(i).attr({'tabindex': '0'});
          } else {
            _.$slides.eq(i).removeAttr('tabindex');
          }
        }

        _.activateADA();

    };

    Slick.prototype.initArrowEvents = function() {

        var _ = this;

        if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {
            _.$prevArrow
               .off('click.slick')
               .on('click.slick', {
                    message: 'previous'
               }, _.changeSlide);
            _.$nextArrow
               .off('click.slick')
               .on('click.slick', {
                    message: 'next'
               }, _.changeSlide);

            if (_.options.accessibility === true) {
                _.$prevArrow.on('keydown.slick', _.keyHandler);
                _.$nextArrow.on('keydown.slick', _.keyHandler);
            }
        }

    };

    Slick.prototype.initDotEvents = function() {

        var _ = this;

        if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {
            $('li', _.$dots).on('click.slick', {
                message: 'index'
            }, _.changeSlide);

            if (_.options.accessibility === true) {
                _.$dots.on('keydown.slick', _.keyHandler);
            }
        }

        if (_.options.dots === true && _.options.pauseOnDotsHover === true && _.slideCount > _.options.slidesToShow) {

            $('li', _.$dots)
                .on('mouseenter.slick', $.proxy(_.interrupt, _, true))
                .on('mouseleave.slick', $.proxy(_.interrupt, _, false));

        }

    };

    Slick.prototype.initSlideEvents = function() {

        var _ = this;

        if ( _.options.pauseOnHover ) {

            _.$list.on('mouseenter.slick', $.proxy(_.interrupt, _, true));
            _.$list.on('mouseleave.slick', $.proxy(_.interrupt, _, false));

        }

    };

    Slick.prototype.initializeEvents = function() {

        var _ = this;

        _.initArrowEvents();

        _.initDotEvents();
        _.initSlideEvents();

        _.$list.on('touchstart.slick mousedown.slick', {
            action: 'start'
        }, _.swipeHandler);
        _.$list.on('touchmove.slick mousemove.slick', {
            action: 'move'
        }, _.swipeHandler);
        _.$list.on('touchend.slick mouseup.slick', {
            action: 'end'
        }, _.swipeHandler);
        _.$list.on('touchcancel.slick mouseleave.slick', {
            action: 'end'
        }, _.swipeHandler);

        _.$list.on('click.slick', _.clickHandler);

        $(document).on(_.visibilityChange, $.proxy(_.visibility, _));

        if (_.options.accessibility === true) {
            _.$list.on('keydown.slick', _.keyHandler);
        }

        if (_.options.focusOnSelect === true) {
            $(_.$slideTrack).children().on('click.slick', _.selectHandler);
        }

        $(window).on('orientationchange.slick.slick-' + _.instanceUid, $.proxy(_.orientationChange, _));

        $(window).on('resize.slick.slick-' + _.instanceUid, $.proxy(_.resize, _));

        $('[draggable!=true]', _.$slideTrack).on('dragstart', _.preventDefault);

        $(window).on('load.slick.slick-' + _.instanceUid, _.setPosition);
        $(_.setPosition);

    };

    Slick.prototype.initUI = function() {

        var _ = this;

        if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {

            _.$prevArrow.show();
            _.$nextArrow.show();

        }

        if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {

            _.$dots.show();

        }

    };

    Slick.prototype.keyHandler = function(event) {

        var _ = this;
         //Dont slide if the cursor is inside the form fields and arrow keys are pressed
        if(!event.target.tagName.match('TEXTAREA|INPUT|SELECT')) {
            if (event.keyCode === 37 && _.options.accessibility === true) {
                _.changeSlide({
                    data: {
                        message: _.options.rtl === true ? 'next' :  'previous'
                    }
                });
            } else if (event.keyCode === 39 && _.options.accessibility === true) {
                _.changeSlide({
                    data: {
                        message: _.options.rtl === true ? 'previous' : 'next'
                    }
                });
            }
        }

    };

    Slick.prototype.lazyLoad = function() {

        var _ = this,
            loadRange, cloneRange, rangeStart, rangeEnd;

        function loadImages(imagesScope) {

            $('img[data-lazy]', imagesScope).each(function() {

                var image = $(this),
                    imageSource = $(this).attr('data-lazy'),
                    imageSrcSet = $(this).attr('data-srcset'),
                    imageSizes  = $(this).attr('data-sizes') || _.$slider.attr('data-sizes'),
                    imageToLoad = document.createElement('img');

                imageToLoad.onload = function() {

                    image
                        .animate({ opacity: 0 }, 100, function() {

                            if (imageSrcSet) {
                                image
                                    .attr('srcset', imageSrcSet );

                                if (imageSizes) {
                                    image
                                        .attr('sizes', imageSizes );
                                }
                            }

                            image
                                .attr('src', imageSource)
                                .animate({ opacity: 1 }, 200, function() {
                                    image
                                        .removeAttr('data-lazy data-srcset data-sizes')
                                        .removeClass('slick-loading');
                                });
                            _.$slider.trigger('lazyLoaded', [_, image, imageSource]);
                        });

                };

                imageToLoad.onerror = function() {

                    image
                        .removeAttr( 'data-lazy' )
                        .removeClass( 'slick-loading' )
                        .addClass( 'slick-lazyload-error' );

                    _.$slider.trigger('lazyLoadError', [ _, image, imageSource ]);

                };

                imageToLoad.src = imageSource;

            });

        }

        if (_.options.centerMode === true) {
            if (_.options.infinite === true) {
                rangeStart = _.currentSlide + (_.options.slidesToShow / 2 + 1);
                rangeEnd = rangeStart + _.options.slidesToShow + 2;
            } else {
                rangeStart = Math.max(0, _.currentSlide - (_.options.slidesToShow / 2 + 1));
                rangeEnd = 2 + (_.options.slidesToShow / 2 + 1) + _.currentSlide;
            }
        } else {
            rangeStart = _.options.infinite ? _.options.slidesToShow + _.currentSlide : _.currentSlide;
            rangeEnd = Math.ceil(rangeStart + _.options.slidesToShow);
            if (_.options.fade === true) {
                if (rangeStart > 0) rangeStart--;
                if (rangeEnd <= _.slideCount) rangeEnd++;
            }
        }

        loadRange = _.$slider.find('.slick-slide').slice(rangeStart, rangeEnd);

        if (_.options.lazyLoad === 'anticipated') {
            var prevSlide = rangeStart - 1,
                nextSlide = rangeEnd,
                $slides = _.$slider.find('.slick-slide');

            for (var i = 0; i < _.options.slidesToScroll; i++) {
                if (prevSlide < 0) prevSlide = _.slideCount - 1;
                loadRange = loadRange.add($slides.eq(prevSlide));
                loadRange = loadRange.add($slides.eq(nextSlide));
                prevSlide--;
                nextSlide++;
            }
        }

        loadImages(loadRange);

        if (_.slideCount <= _.options.slidesToShow) {
            cloneRange = _.$slider.find('.slick-slide');
            loadImages(cloneRange);
        } else
        if (_.currentSlide >= _.slideCount - _.options.slidesToShow) {
            cloneRange = _.$slider.find('.slick-cloned').slice(0, _.options.slidesToShow);
            loadImages(cloneRange);
        } else if (_.currentSlide === 0) {
            cloneRange = _.$slider.find('.slick-cloned').slice(_.options.slidesToShow * -1);
            loadImages(cloneRange);
        }

    };

    Slick.prototype.loadSlider = function() {

        var _ = this;

        _.setPosition();

        _.$slideTrack.css({
            opacity: 1
        });

        _.$slider.removeClass('slick-loading');

        _.initUI();

        if (_.options.lazyLoad === 'progressive') {
            _.progressiveLazyLoad();
        }

    };

    Slick.prototype.next = Slick.prototype.slickNext = function() {

        var _ = this;

        _.changeSlide({
            data: {
                message: 'next'
            }
        });

    };

    Slick.prototype.orientationChange = function() {

        var _ = this;

        _.checkResponsive();
        _.setPosition();

    };

    Slick.prototype.pause = Slick.prototype.slickPause = function() {

        var _ = this;

        _.autoPlayClear();
        _.paused = true;

    };

    Slick.prototype.play = Slick.prototype.slickPlay = function() {

        var _ = this;

        _.autoPlay();
        _.options.autoplay = true;
        _.paused = false;
        _.focussed = false;
        _.interrupted = false;

    };

    Slick.prototype.postSlide = function(index) {

        var _ = this;

        if( !_.unslicked ) {

            _.$slider.trigger('afterChange', [_, index]);

            _.animating = false;

            if (_.slideCount > _.options.slidesToShow) {
                _.setPosition();
            }

            _.swipeLeft = null;

            if ( _.options.autoplay ) {
                _.autoPlay();
            }

            if (_.options.accessibility === true) {
                _.initADA();

                if (_.options.focusOnChange) {
                    var $currentSlide = $(_.$slides.get(_.currentSlide));
                    $currentSlide.attr('tabindex', 0).focus();
                }
            }

        }

    };

    Slick.prototype.prev = Slick.prototype.slickPrev = function() {

        var _ = this;

        _.changeSlide({
            data: {
                message: 'previous'
            }
        });

    };

    Slick.prototype.preventDefault = function(event) {

        event.preventDefault();

    };

    Slick.prototype.progressiveLazyLoad = function( tryCount ) {

        tryCount = tryCount || 1;

        var _ = this,
            $imgsToLoad = $( 'img[data-lazy]', _.$slider ),
            image,
            imageSource,
            imageSrcSet,
            imageSizes,
            imageToLoad;

        if ( $imgsToLoad.length ) {

            image = $imgsToLoad.first();
            imageSource = image.attr('data-lazy');
            imageSrcSet = image.attr('data-srcset');
            imageSizes  = image.attr('data-sizes') || _.$slider.attr('data-sizes');
            imageToLoad = document.createElement('img');

            imageToLoad.onload = function() {

                if (imageSrcSet) {
                    image
                        .attr('srcset', imageSrcSet );

                    if (imageSizes) {
                        image
                            .attr('sizes', imageSizes );
                    }
                }

                image
                    .attr( 'src', imageSource )
                    .removeAttr('data-lazy data-srcset data-sizes')
                    .removeClass('slick-loading');

                if ( _.options.adaptiveHeight === true ) {
                    _.setPosition();
                }

                _.$slider.trigger('lazyLoaded', [ _, image, imageSource ]);
                _.progressiveLazyLoad();

            };

            imageToLoad.onerror = function() {

                if ( tryCount < 3 ) {

                    /**
                     * try to load the image 3 times,
                     * leave a slight delay so we don't get
                     * servers blocking the request.
                     */
                    setTimeout( function() {
                        _.progressiveLazyLoad( tryCount + 1 );
                    }, 500 );

                } else {

                    image
                        .removeAttr( 'data-lazy' )
                        .removeClass( 'slick-loading' )
                        .addClass( 'slick-lazyload-error' );

                    _.$slider.trigger('lazyLoadError', [ _, image, imageSource ]);

                    _.progressiveLazyLoad();

                }

            };

            imageToLoad.src = imageSource;

        } else {

            _.$slider.trigger('allImagesLoaded', [ _ ]);

        }

    };

    Slick.prototype.refresh = function( initializing ) {

        var _ = this, currentSlide, lastVisibleIndex;

        lastVisibleIndex = _.slideCount - _.options.slidesToShow;

        // in non-infinite sliders, we don't want to go past the
        // last visible index.
        if( !_.options.infinite && ( _.currentSlide > lastVisibleIndex )) {
            _.currentSlide = lastVisibleIndex;
        }

        // if less slides than to show, go to start.
        if ( _.slideCount <= _.options.slidesToShow ) {
            _.currentSlide = 0;

        }

        currentSlide = _.currentSlide;

        _.destroy(true);

        $.extend(_, _.initials, { currentSlide: currentSlide });

        _.init();

        if( !initializing ) {

            _.changeSlide({
                data: {
                    message: 'index',
                    index: currentSlide
                }
            }, false);

        }

    };

    Slick.prototype.registerBreakpoints = function() {

        var _ = this, breakpoint, currentBreakpoint, l,
            responsiveSettings = _.options.responsive || null;

        if ( $.type(responsiveSettings) === 'array' && responsiveSettings.length ) {

            _.respondTo = _.options.respondTo || 'window';

            for ( breakpoint in responsiveSettings ) {

                l = _.breakpoints.length-1;

                if (responsiveSettings.hasOwnProperty(breakpoint)) {
                    currentBreakpoint = responsiveSettings[breakpoint].breakpoint;

                    // loop through the breakpoints and cut out any existing
                    // ones with the same breakpoint number, we don't want dupes.
                    while( l >= 0 ) {
                        if( _.breakpoints[l] && _.breakpoints[l] === currentBreakpoint ) {
                            _.breakpoints.splice(l,1);
                        }
                        l--;
                    }

                    _.breakpoints.push(currentBreakpoint);
                    _.breakpointSettings[currentBreakpoint] = responsiveSettings[breakpoint].settings;

                }

            }

            _.breakpoints.sort(function(a, b) {
                return ( _.options.mobileFirst ) ? a-b : b-a;
            });

        }

    };

    Slick.prototype.reinit = function() {

        var _ = this;

        _.$slides =
            _.$slideTrack
                .children(_.options.slide)
                .addClass('slick-slide');

        _.slideCount = _.$slides.length;

        if (_.currentSlide >= _.slideCount && _.currentSlide !== 0) {
            _.currentSlide = _.currentSlide - _.options.slidesToScroll;
        }

        if (_.slideCount <= _.options.slidesToShow) {
            _.currentSlide = 0;
        }

        _.registerBreakpoints();

        _.setProps();
        _.setupInfinite();
        _.buildArrows();
        _.updateArrows();
        _.initArrowEvents();
        _.buildDots();
        _.updateDots();
        _.initDotEvents();
        _.cleanUpSlideEvents();
        _.initSlideEvents();

        _.checkResponsive(false, true);

        if (_.options.focusOnSelect === true) {
            $(_.$slideTrack).children().on('click.slick', _.selectHandler);
        }

        _.setSlideClasses(typeof _.currentSlide === 'number' ? _.currentSlide : 0);

        _.setPosition();
        _.focusHandler();

        _.paused = !_.options.autoplay;
        _.autoPlay();

        _.$slider.trigger('reInit', [_]);

    };

    Slick.prototype.resize = function() {

        var _ = this;

        if ($(window).width() !== _.windowWidth) {
            clearTimeout(_.windowDelay);
            _.windowDelay = window.setTimeout(function() {
                _.windowWidth = $(window).width();
                _.checkResponsive();
                if( !_.unslicked ) { _.setPosition(); }
            }, 50);
        }
    };

    Slick.prototype.removeSlide = Slick.prototype.slickRemove = function(index, removeBefore, removeAll) {

        var _ = this;

        if (typeof(index) === 'boolean') {
            removeBefore = index;
            index = removeBefore === true ? 0 : _.slideCount - 1;
        } else {
            index = removeBefore === true ? --index : index;
        }

        if (_.slideCount < 1 || index < 0 || index > _.slideCount - 1) {
            return false;
        }

        _.unload();

        if (removeAll === true) {
            _.$slideTrack.children().remove();
        } else {
            _.$slideTrack.children(this.options.slide).eq(index).remove();
        }

        _.$slides = _.$slideTrack.children(this.options.slide);

        _.$slideTrack.children(this.options.slide).detach();

        _.$slideTrack.append(_.$slides);

        _.$slidesCache = _.$slides;

        _.reinit();

    };

    Slick.prototype.setCSS = function(position) {

        var _ = this,
            positionProps = {},
            x, y;

        if (_.options.rtl === true) {
            position = -position;
        }
        x = _.positionProp == 'left' ? Math.ceil(position) + 'px' : '0px';
        y = _.positionProp == 'top' ? Math.ceil(position) + 'px' : '0px';

        positionProps[_.positionProp] = position;

        if (_.transformsEnabled === false) {
            _.$slideTrack.css(positionProps);
        } else {
            positionProps = {};
            if (_.cssTransitions === false) {
                positionProps[_.animType] = 'translate(' + x + ', ' + y + ')';
                _.$slideTrack.css(positionProps);
            } else {
                positionProps[_.animType] = 'translate3d(' + x + ', ' + y + ', 0px)';
                _.$slideTrack.css(positionProps);
            }
        }

    };

    Slick.prototype.setDimensions = function() {

        var _ = this;

        if (_.options.vertical === false) {
            if (_.options.centerMode === true) {
                _.$list.css({
                    padding: ('0px ' + _.options.centerPadding)
                });
            }
        } else {
            _.$list.height(_.$slides.first().outerHeight(true) * _.options.slidesToShow);
            if (_.options.centerMode === true) {
                _.$list.css({
                    padding: (_.options.centerPadding + ' 0px')
                });
            }
        }

        _.listWidth = _.$list.width();
        _.listHeight = _.$list.height();


        if (_.options.vertical === false && _.options.variableWidth === false) {
            _.slideWidth = Math.ceil(_.listWidth / _.options.slidesToShow);
            _.$slideTrack.width(Math.ceil((_.slideWidth * _.$slideTrack.children('.slick-slide').length)));

        } else if (_.options.variableWidth === true) {
            _.$slideTrack.width(5000 * _.slideCount);
        } else {
            _.slideWidth = Math.ceil(_.listWidth);
            _.$slideTrack.height(Math.ceil((_.$slides.first().outerHeight(true) * _.$slideTrack.children('.slick-slide').length)));
        }

        var offset = _.$slides.first().outerWidth(true) - _.$slides.first().width();
        if (_.options.variableWidth === false) _.$slideTrack.children('.slick-slide').width(_.slideWidth - offset);

    };

    Slick.prototype.setFade = function() {

        var _ = this,
            targetLeft;

        _.$slides.each(function(index, element) {
            targetLeft = (_.slideWidth * index) * -1;
            if (_.options.rtl === true) {
                $(element).css({
                    position: 'relative',
                    right: targetLeft,
                    top: 0,
                    zIndex: _.options.zIndex - 2,
                    opacity: 0
                });
            } else {
                $(element).css({
                    position: 'relative',
                    left: targetLeft,
                    top: 0,
                    zIndex: _.options.zIndex - 2,
                    opacity: 0
                });
            }
        });

        _.$slides.eq(_.currentSlide).css({
            zIndex: _.options.zIndex - 1,
            opacity: 1
        });

    };

    Slick.prototype.setHeight = function() {

        var _ = this;

        if (_.options.slidesToShow === 1 && _.options.adaptiveHeight === true && _.options.vertical === false) {
            var targetHeight = _.$slides.eq(_.currentSlide).outerHeight(true);
            _.$list.css('height', targetHeight);
        }

    };

    Slick.prototype.setOption =
    Slick.prototype.slickSetOption = function() {

        /**
         * accepts arguments in format of:
         *
         *  - for changing a single option's value:
         *     .slick("setOption", option, value, refresh )
         *
         *  - for changing a set of responsive options:
         *     .slick("setOption", 'responsive', [{}, ...], refresh )
         *
         *  - for updating multiple values at once (not responsive)
         *     .slick("setOption", { 'option': value, ... }, refresh )
         */

        var _ = this, l, item, option, value, refresh = false, type;

        if( $.type( arguments[0] ) === 'object' ) {

            option =  arguments[0];
            refresh = arguments[1];
            type = 'multiple';

        } else if ( $.type( arguments[0] ) === 'string' ) {

            option =  arguments[0];
            value = arguments[1];
            refresh = arguments[2];

            if ( arguments[0] === 'responsive' && $.type( arguments[1] ) === 'array' ) {

                type = 'responsive';

            } else if ( typeof arguments[1] !== 'undefined' ) {

                type = 'single';

            }

        }

        if ( type === 'single' ) {

            _.options[option] = value;


        } else if ( type === 'multiple' ) {

            $.each( option , function( opt, val ) {

                _.options[opt] = val;

            });


        } else if ( type === 'responsive' ) {

            for ( item in value ) {

                if( $.type( _.options.responsive ) !== 'array' ) {

                    _.options.responsive = [ value[item] ];

                } else {

                    l = _.options.responsive.length-1;

                    // loop through the responsive object and splice out duplicates.
                    while( l >= 0 ) {

                        if( _.options.responsive[l].breakpoint === value[item].breakpoint ) {

                            _.options.responsive.splice(l,1);

                        }

                        l--;

                    }

                    _.options.responsive.push( value[item] );

                }

            }

        }

        if ( refresh ) {

            _.unload();
            _.reinit();

        }

    };

    Slick.prototype.setPosition = function() {

        var _ = this;

        _.setDimensions();

        _.setHeight();

        if (_.options.fade === false) {
            _.setCSS(_.getLeft(_.currentSlide));
        } else {
            _.setFade();
        }

        _.$slider.trigger('setPosition', [_]);

    };

    Slick.prototype.setProps = function() {

        var _ = this,
            bodyStyle = document.body.style;

        _.positionProp = _.options.vertical === true ? 'top' : 'left';

        if (_.positionProp === 'top') {
            _.$slider.addClass('slick-vertical');
        } else {
            _.$slider.removeClass('slick-vertical');
        }

        if (bodyStyle.WebkitTransition !== undefined ||
            bodyStyle.MozTransition !== undefined ||
            bodyStyle.msTransition !== undefined) {
            if (_.options.useCSS === true) {
                _.cssTransitions = true;
            }
        }

        if ( _.options.fade ) {
            if ( typeof _.options.zIndex === 'number' ) {
                if( _.options.zIndex < 3 ) {
                    _.options.zIndex = 3;
                }
            } else {
                _.options.zIndex = _.defaults.zIndex;
            }
        }

        if (bodyStyle.OTransform !== undefined) {
            _.animType = 'OTransform';
            _.transformType = '-o-transform';
            _.transitionType = 'OTransition';
            if (bodyStyle.perspectiveProperty === undefined && bodyStyle.webkitPerspective === undefined) _.animType = false;
        }
        if (bodyStyle.MozTransform !== undefined) {
            _.animType = 'MozTransform';
            _.transformType = '-moz-transform';
            _.transitionType = 'MozTransition';
            if (bodyStyle.perspectiveProperty === undefined && bodyStyle.MozPerspective === undefined) _.animType = false;
        }
        if (bodyStyle.webkitTransform !== undefined) {
            _.animType = 'webkitTransform';
            _.transformType = '-webkit-transform';
            _.transitionType = 'webkitTransition';
            if (bodyStyle.perspectiveProperty === undefined && bodyStyle.webkitPerspective === undefined) _.animType = false;
        }
        if (bodyStyle.msTransform !== undefined) {
            _.animType = 'msTransform';
            _.transformType = '-ms-transform';
            _.transitionType = 'msTransition';
            if (bodyStyle.msTransform === undefined) _.animType = false;
        }
        if (bodyStyle.transform !== undefined && _.animType !== false) {
            _.animType = 'transform';
            _.transformType = 'transform';
            _.transitionType = 'transition';
        }
        _.transformsEnabled = _.options.useTransform && (_.animType !== null && _.animType !== false);
    };


    Slick.prototype.setSlideClasses = function(index) {

        var _ = this,
            centerOffset, allSlides, indexOffset, remainder;

        allSlides = _.$slider
            .find('.slick-slide')
            .removeClass('slick-active slick-center slick-current')
            .attr('aria-hidden', 'true');

        _.$slides
            .eq(index)
            .addClass('slick-current');

        if (_.options.centerMode === true) {

            var evenCoef = _.options.slidesToShow % 2 === 0 ? 1 : 0;

            centerOffset = Math.floor(_.options.slidesToShow / 2);

            if (_.options.infinite === true) {

                if (index >= centerOffset && index <= (_.slideCount - 1) - centerOffset) {
                    _.$slides
                        .slice(index - centerOffset + evenCoef, index + centerOffset + 1)
                        .addClass('slick-active')
                        .attr('aria-hidden', 'false');

                } else {

                    indexOffset = _.options.slidesToShow + index;
                    allSlides
                        .slice(indexOffset - centerOffset + 1 + evenCoef, indexOffset + centerOffset + 2)
                        .addClass('slick-active')
                        .attr('aria-hidden', 'false');

                }

                if (index === 0) {

                    allSlides
                        .eq(allSlides.length - 1 - _.options.slidesToShow)
                        .addClass('slick-center');

                } else if (index === _.slideCount - 1) {

                    allSlides
                        .eq(_.options.slidesToShow)
                        .addClass('slick-center');

                }

            }

            _.$slides
                .eq(index)
                .addClass('slick-center');

        } else {

            if (index >= 0 && index <= (_.slideCount - _.options.slidesToShow)) {

                _.$slides
                    .slice(index, index + _.options.slidesToShow)
                    .addClass('slick-active')
                    .attr('aria-hidden', 'false');

            } else if (allSlides.length <= _.options.slidesToShow) {

                allSlides
                    .addClass('slick-active')
                    .attr('aria-hidden', 'false');

            } else {

                remainder = _.slideCount % _.options.slidesToShow;
                indexOffset = _.options.infinite === true ? _.options.slidesToShow + index : index;

                if (_.options.slidesToShow == _.options.slidesToScroll && (_.slideCount - index) < _.options.slidesToShow) {

                    allSlides
                        .slice(indexOffset - (_.options.slidesToShow - remainder), indexOffset + remainder)
                        .addClass('slick-active')
                        .attr('aria-hidden', 'false');

                } else {

                    allSlides
                        .slice(indexOffset, indexOffset + _.options.slidesToShow)
                        .addClass('slick-active')
                        .attr('aria-hidden', 'false');

                }

            }

        }

        if (_.options.lazyLoad === 'ondemand' || _.options.lazyLoad === 'anticipated') {
            _.lazyLoad();
        }
    };

    Slick.prototype.setupInfinite = function() {

        var _ = this,
            i, slideIndex, infiniteCount;

        if (_.options.fade === true) {
            _.options.centerMode = false;
        }

        if (_.options.infinite === true && _.options.fade === false) {

            slideIndex = null;

            if (_.slideCount > _.options.slidesToShow) {

                if (_.options.centerMode === true) {
                    infiniteCount = _.options.slidesToShow + 1;
                } else {
                    infiniteCount = _.options.slidesToShow;
                }

                for (i = _.slideCount; i > (_.slideCount -
                        infiniteCount); i -= 1) {
                    slideIndex = i - 1;
                    $(_.$slides[slideIndex]).clone(true).attr('id', '')
                        .attr('data-slick-index', slideIndex - _.slideCount)
                        .prependTo(_.$slideTrack).addClass('slick-cloned');
                }
                for (i = 0; i < infiniteCount  + _.slideCount; i += 1) {
                    slideIndex = i;
                    $(_.$slides[slideIndex]).clone(true).attr('id', '')
                        .attr('data-slick-index', slideIndex + _.slideCount)
                        .appendTo(_.$slideTrack).addClass('slick-cloned');
                }
                _.$slideTrack.find('.slick-cloned').find('[id]').each(function() {
                    $(this).attr('id', '');
                });

            }

        }

    };

    Slick.prototype.interrupt = function( toggle ) {

        var _ = this;

        if( !toggle ) {
            _.autoPlay();
        }
        _.interrupted = toggle;

    };

    Slick.prototype.selectHandler = function(event) {

        var _ = this;

        var targetElement =
            $(event.target).is('.slick-slide') ?
                $(event.target) :
                $(event.target).parents('.slick-slide');

        var index = parseInt(targetElement.attr('data-slick-index'));

        if (!index) index = 0;

        if (_.slideCount <= _.options.slidesToShow) {

            _.slideHandler(index, false, true);
            return;

        }

        _.slideHandler(index);

    };

    Slick.prototype.slideHandler = function(index, sync, dontAnimate) {

        var targetSlide, animSlide, oldSlide, slideLeft, targetLeft = null,
            _ = this, navTarget;

        sync = sync || false;

        if (_.animating === true && _.options.waitForAnimate === true) {
            return;
        }

        if (_.options.fade === true && _.currentSlide === index) {
            return;
        }

        if (sync === false) {
            _.asNavFor(index);
        }

        targetSlide = index;
        targetLeft = _.getLeft(targetSlide);
        slideLeft = _.getLeft(_.currentSlide);

        _.currentLeft = _.swipeLeft === null ? slideLeft : _.swipeLeft;

        if (_.options.infinite === false && _.options.centerMode === false && (index < 0 || index > _.getDotCount() * _.options.slidesToScroll)) {
            if (_.options.fade === false) {
                targetSlide = _.currentSlide;
                if (dontAnimate !== true && _.slideCount > _.options.slidesToShow) {
                    _.animateSlide(slideLeft, function() {
                        _.postSlide(targetSlide);
                    });
                } else {
                    _.postSlide(targetSlide);
                }
            }
            return;
        } else if (_.options.infinite === false && _.options.centerMode === true && (index < 0 || index > (_.slideCount - _.options.slidesToScroll))) {
            if (_.options.fade === false) {
                targetSlide = _.currentSlide;
                if (dontAnimate !== true && _.slideCount > _.options.slidesToShow) {
                    _.animateSlide(slideLeft, function() {
                        _.postSlide(targetSlide);
                    });
                } else {
                    _.postSlide(targetSlide);
                }
            }
            return;
        }

        if ( _.options.autoplay ) {
            clearInterval(_.autoPlayTimer);
        }

        if (targetSlide < 0) {
            if (_.slideCount % _.options.slidesToScroll !== 0) {
                animSlide = _.slideCount - (_.slideCount % _.options.slidesToScroll);
            } else {
                animSlide = _.slideCount + targetSlide;
            }
        } else if (targetSlide >= _.slideCount) {
            if (_.slideCount % _.options.slidesToScroll !== 0) {
                animSlide = 0;
            } else {
                animSlide = targetSlide - _.slideCount;
            }
        } else {
            animSlide = targetSlide;
        }

        _.animating = true;

        _.$slider.trigger('beforeChange', [_, _.currentSlide, animSlide]);

        oldSlide = _.currentSlide;
        _.currentSlide = animSlide;

        _.setSlideClasses(_.currentSlide);

        if ( _.options.asNavFor ) {

            navTarget = _.getNavTarget();
            navTarget = navTarget.slick('getSlick');

            if ( navTarget.slideCount <= navTarget.options.slidesToShow ) {
                navTarget.setSlideClasses(_.currentSlide);
            }

        }

        _.updateDots();
        _.updateArrows();

        if (_.options.fade === true) {
            if (dontAnimate !== true) {

                _.fadeSlideOut(oldSlide);

                _.fadeSlide(animSlide, function() {
                    _.postSlide(animSlide);
                });

            } else {
                _.postSlide(animSlide);
            }
            _.animateHeight();
            return;
        }

        if (dontAnimate !== true && _.slideCount > _.options.slidesToShow) {
            _.animateSlide(targetLeft, function() {
                _.postSlide(animSlide);
            });
        } else {
            _.postSlide(animSlide);
        }

    };

    Slick.prototype.startLoad = function() {

        var _ = this;

        if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {

            _.$prevArrow.hide();
            _.$nextArrow.hide();

        }

        if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {

            _.$dots.hide();

        }

        _.$slider.addClass('slick-loading');

    };

    Slick.prototype.swipeDirection = function() {

        var xDist, yDist, r, swipeAngle, _ = this;

        xDist = _.touchObject.startX - _.touchObject.curX;
        yDist = _.touchObject.startY - _.touchObject.curY;
        r = Math.atan2(yDist, xDist);

        swipeAngle = Math.round(r * 180 / Math.PI);
        if (swipeAngle < 0) {
            swipeAngle = 360 - Math.abs(swipeAngle);
        }

        if ((swipeAngle <= 45) && (swipeAngle >= 0)) {
            return (_.options.rtl === false ? 'left' : 'right');
        }
        if ((swipeAngle <= 360) && (swipeAngle >= 315)) {
            return (_.options.rtl === false ? 'left' : 'right');
        }
        if ((swipeAngle >= 135) && (swipeAngle <= 225)) {
            return (_.options.rtl === false ? 'right' : 'left');
        }
        if (_.options.verticalSwiping === true) {
            if ((swipeAngle >= 35) && (swipeAngle <= 135)) {
                return 'down';
            } else {
                return 'up';
            }
        }

        return 'vertical';

    };

    Slick.prototype.swipeEnd = function(event) {

        var _ = this,
            slideCount,
            direction;

        _.dragging = false;
        _.swiping = false;

        if (_.scrolling) {
            _.scrolling = false;
            return false;
        }

        _.interrupted = false;
        _.shouldClick = ( _.touchObject.swipeLength > 10 ) ? false : true;

        if ( _.touchObject.curX === undefined ) {
            return false;
        }

        if ( _.touchObject.edgeHit === true ) {
            _.$slider.trigger('edge', [_, _.swipeDirection() ]);
        }

        if ( _.touchObject.swipeLength >= _.touchObject.minSwipe ) {

            direction = _.swipeDirection();

            switch ( direction ) {

                case 'left':
                case 'down':

                    slideCount =
                        _.options.swipeToSlide ?
                            _.checkNavigable( _.currentSlide + _.getSlideCount() ) :
                            _.currentSlide + _.getSlideCount();

                    _.currentDirection = 0;

                    break;

                case 'right':
                case 'up':

                    slideCount =
                        _.options.swipeToSlide ?
                            _.checkNavigable( _.currentSlide - _.getSlideCount() ) :
                            _.currentSlide - _.getSlideCount();

                    _.currentDirection = 1;

                    break;

                default:


            }

            if( direction != 'vertical' ) {

                _.slideHandler( slideCount );
                _.touchObject = {};
                _.$slider.trigger('swipe', [_, direction ]);

            }

        } else {

            if ( _.touchObject.startX !== _.touchObject.curX ) {

                _.slideHandler( _.currentSlide );
                _.touchObject = {};

            }

        }

    };

    Slick.prototype.swipeHandler = function(event) {

        var _ = this;

        if ((_.options.swipe === false) || ('ontouchend' in document && _.options.swipe === false)) {
            return;
        } else if (_.options.draggable === false && event.type.indexOf('mouse') !== -1) {
            return;
        }

        _.touchObject.fingerCount = event.originalEvent && event.originalEvent.touches !== undefined ?
            event.originalEvent.touches.length : 1;

        _.touchObject.minSwipe = _.listWidth / _.options
            .touchThreshold;

        if (_.options.verticalSwiping === true) {
            _.touchObject.minSwipe = _.listHeight / _.options
                .touchThreshold;
        }

        switch (event.data.action) {

            case 'start':
                _.swipeStart(event);
                break;

            case 'move':
                _.swipeMove(event);
                break;

            case 'end':
                _.swipeEnd(event);
                break;

        }

    };

    Slick.prototype.swipeMove = function(event) {

        var _ = this,
            edgeWasHit = false,
            curLeft, swipeDirection, swipeLength, positionOffset, touches, verticalSwipeLength;

        touches = event.originalEvent !== undefined ? event.originalEvent.touches : null;

        if (!_.dragging || _.scrolling || touches && touches.length !== 1) {
            return false;
        }

        curLeft = _.getLeft(_.currentSlide);

        _.touchObject.curX = touches !== undefined ? touches[0].pageX : event.clientX;
        _.touchObject.curY = touches !== undefined ? touches[0].pageY : event.clientY;

        _.touchObject.swipeLength = Math.round(Math.sqrt(
            Math.pow(_.touchObject.curX - _.touchObject.startX, 2)));

        verticalSwipeLength = Math.round(Math.sqrt(
            Math.pow(_.touchObject.curY - _.touchObject.startY, 2)));

        if (!_.options.verticalSwiping && !_.swiping && verticalSwipeLength > 4) {
            _.scrolling = true;
            return false;
        }

        if (_.options.verticalSwiping === true) {
            _.touchObject.swipeLength = verticalSwipeLength;
        }

        swipeDirection = _.swipeDirection();

        if (event.originalEvent !== undefined && _.touchObject.swipeLength > 4) {
            _.swiping = true;
            event.preventDefault();
        }

        positionOffset = (_.options.rtl === false ? 1 : -1) * (_.touchObject.curX > _.touchObject.startX ? 1 : -1);
        if (_.options.verticalSwiping === true) {
            positionOffset = _.touchObject.curY > _.touchObject.startY ? 1 : -1;
        }


        swipeLength = _.touchObject.swipeLength;

        _.touchObject.edgeHit = false;

        if (_.options.infinite === false) {
            if ((_.currentSlide === 0 && swipeDirection === 'right') || (_.currentSlide >= _.getDotCount() && swipeDirection === 'left')) {
                swipeLength = _.touchObject.swipeLength * _.options.edgeFriction;
                _.touchObject.edgeHit = true;
            }
        }

        if (_.options.vertical === false) {
            _.swipeLeft = curLeft + swipeLength * positionOffset;
        } else {
            _.swipeLeft = curLeft + (swipeLength * (_.$list.height() / _.listWidth)) * positionOffset;
        }
        if (_.options.verticalSwiping === true) {
            _.swipeLeft = curLeft + swipeLength * positionOffset;
        }

        if (_.options.fade === true || _.options.touchMove === false) {
            return false;
        }

        if (_.animating === true) {
            _.swipeLeft = null;
            return false;
        }

        _.setCSS(_.swipeLeft);

    };

    Slick.prototype.swipeStart = function(event) {

        var _ = this,
            touches;

        _.interrupted = true;

        if (_.touchObject.fingerCount !== 1 || _.slideCount <= _.options.slidesToShow) {
            _.touchObject = {};
            return false;
        }

        if (event.originalEvent !== undefined && event.originalEvent.touches !== undefined) {
            touches = event.originalEvent.touches[0];
        }

        _.touchObject.startX = _.touchObject.curX = touches !== undefined ? touches.pageX : event.clientX;
        _.touchObject.startY = _.touchObject.curY = touches !== undefined ? touches.pageY : event.clientY;

        _.dragging = true;

    };

    Slick.prototype.unfilterSlides = Slick.prototype.slickUnfilter = function() {

        var _ = this;

        if (_.$slidesCache !== null) {

            _.unload();

            _.$slideTrack.children(this.options.slide).detach();

            _.$slidesCache.appendTo(_.$slideTrack);

            _.reinit();

        }

    };

    Slick.prototype.unload = function() {

        var _ = this;

        $('.slick-cloned', _.$slider).remove();

        if (_.$dots) {
            _.$dots.remove();
        }

        if (_.$prevArrow && _.htmlExpr.test(_.options.prevArrow)) {
            _.$prevArrow.remove();
        }

        if (_.$nextArrow && _.htmlExpr.test(_.options.nextArrow)) {
            _.$nextArrow.remove();
        }

        _.$slides
            .removeClass('slick-slide slick-active slick-visible slick-current')
            .attr('aria-hidden', 'true')
            .css('width', '');

    };

    Slick.prototype.unslick = function(fromBreakpoint) {

        var _ = this;
        _.$slider.trigger('unslick', [_, fromBreakpoint]);
        _.destroy();

    };

    Slick.prototype.updateArrows = function() {

        var _ = this,
            centerOffset;

        centerOffset = Math.floor(_.options.slidesToShow / 2);

        if ( _.options.arrows === true &&
            _.slideCount > _.options.slidesToShow &&
            !_.options.infinite ) {

            _.$prevArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');
            _.$nextArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');

            if (_.currentSlide === 0) {

                _.$prevArrow.addClass('slick-disabled').attr('aria-disabled', 'true');
                _.$nextArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');

            } else if (_.currentSlide >= _.slideCount - _.options.slidesToShow && _.options.centerMode === false) {

                _.$nextArrow.addClass('slick-disabled').attr('aria-disabled', 'true');
                _.$prevArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');

            } else if (_.currentSlide >= _.slideCount - 1 && _.options.centerMode === true) {

                _.$nextArrow.addClass('slick-disabled').attr('aria-disabled', 'true');
                _.$prevArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');

            }

        }

    };

    Slick.prototype.updateDots = function() {

        var _ = this;

        if (_.$dots !== null) {

            _.$dots
                .find('li')
                    .removeClass('slick-active')
                    .end();

            _.$dots
                .find('li')
                .eq(Math.floor(_.currentSlide / _.options.slidesToScroll))
                .addClass('slick-active');

        }

    };

    Slick.prototype.visibility = function() {

        var _ = this;

        if ( _.options.autoplay ) {

            if ( document[_.hidden] ) {

                _.interrupted = true;

            } else {

                _.interrupted = false;

            }

        }

    };

    $.fn.slick = function() {
        var _ = this,
            opt = arguments[0],
            args = Array.prototype.slice.call(arguments, 1),
            l = _.length,
            i,
            ret;
        for (i = 0; i < l; i++) {
            if (typeof opt == 'object' || typeof opt == 'undefined')
                _[i].slick = new Slick(_[i], opt);
            else
                ret = _[i].slick[opt].apply(_[i].slick, args);
            if (typeof ret != 'undefined') return ret;
        }
        return _;
    };

}));

/* Location Product Tab Functionality Start */
$(window).load(function() {

    var locationTotalPaginationPages = 0;
    var productTotalPages = 0;
    var dataRefineTab;

    var regionfirstdata, countryfirstdata;

    /** on load ajax call **/
    /*
     * This ajax function is used to get all the location data on page load
     *
     */
    var refine = $("#contact-myTab li.active a").attr("data-refine");
    var locationsJsonPath = $("#contact-myTab-loc a").attr("data-file-path");
    dataRefineTab = refine;
    var refineData = $("#contact-myTab li.active a").attr("href");
    var locationRecords = '';

    var findAnOfficeApiUrl = DOMPurify.sanitize($(".find-office-wrapper").attr("data-find-an-office-api-url"));
    var locationsRegion = $.ajax({
        url: findAnOfficeApiUrl,
        type: "GET",
        dataType: "json",
        cache: false,
        data: {
            valueNeeded: "locations",
            locationsJsonPath: locationsJsonPath
        },
        success: function(data) {
            locationRecords = data;
            
            refine = 'locations';
            if (data.hasOwnProperty(refine)) {

                $("#home1").find(".region-dropdown ul").children('li').remove();
                for (var regionData in data[refine]) {

                    $("#home1").find(".region-dropdown ul").append("<li><a href='javascript:void(0);' class='olam-text-p4'>" + DOMPurify.sanitize(regionData) + "</a></li>");

                }
            }
            /*On page load data Start */
            if( document.querySelector("#home1 .region-dropdown ul li a") != null)
            regionfirstdata = document.querySelector("#home1 .region-dropdown ul li a").innerText;


            for (var countryData in locationRecords[refine][regionfirstdata]) {
             
                $("#home1 .country-dropdown ul").append("<li><a href='javascript:void(0);' class='olam-text-p4'>" + DOMPurify.sanitize(countryData) + "</a></li>");
            }
            countryfirstdata = $("#home1 .country-dropdown ul li:first a").html();
            $("#home1 .country-dropdown ul").children('li').remove();
            loctaionsDataLoad(regionfirstdata, countryfirstdata);

            /*On page load data End */
        }
    });

    /*
     * This ajax function is used to get all the product data on page load
     *
     */
    var productsRecords = '';
    var productsJsonPath = $("#contact-myTab-prod a").attr("data-file-path");
    var productsProduct = $.ajax({
        url: findAnOfficeApiUrl,
        type: "GET",
        dataType: "json",
        cache: false,
        data: {
            valueNeeded: "products",
            productsJsonPath: productsJsonPath
        },
        success: function(data) {
            productsRecords = data;
            if (data.hasOwnProperty('products')) {
                $("#home2").find(".product-dropdown ul").children('li').remove();
                for (var regionData in data['products']) {
                    $("#home2").find(".product-dropdown ul").append("<li><a href='javascript:void(0);' class='olam-text-p4'>" + DOMPurify.sanitize(regionData) + "</a></li>");
                }
            }
        }
    });

    /** on load ajax call **/

    /*
     * This event is used for expand & collapse
     */
    /*
    $(".lp-dropdown-active").click(function() {
        $(this).find('.glyphicon').toggleClass('glyphicon-menu-down glyphicon-menu-up');
        $(this).next().slideToggle();
    });
    */

    /**
     *  This function will return the pagination number's in array format
     *
     *  @param integer c is the current page or selected pagination value
     *  @param integer m is the total pagination value.
     */
    function pagination(c, m) {
        var current = c;
        var last = m;
        var delta = 2;
        var left = current - delta;
        var right = current + delta + 1;
        var range = [];
        var rangeWithDots = [];
        var l;

        for (var i = 1; i <= last; i++) {
            if (i == 1 || i == last || i >= left && i < right) {
                range.push(i);
            }
        }

        for (var i = 0; i < range.length; i++) {
            if (l) {
                if (range[i] - l === 2) {
                    rangeWithDots.push(l + 1);
                } else if (range[i] - l !== 1) {
                    rangeWithDots.push("...");
                }
            }
            rangeWithDots.push(range[i]);
            l = range[i];
        }

        return rangeWithDots;
    }

    var perPage = 3;
    var currentPage = 1;
    var totalPages, pages, activePage;

    /**
     *  This event is used to trigger selected pagination.
     */
    $("body").on("click", ".pagination-item:not(.js-disabled)", function() {
        if ($(this).parents(".pagination-wrapper").parent().hasClass("lp-content-wrapper")) {
            dataRefineTab = $("#contact-myTab li.active a").attr("data-refine");
            var prev = $(this).hasClass("js-page-prev");
            var next = $(this).hasClass("js-page-next");
            if (prev) {
                currentPage = $(".pagination-item.active").text();
                currentPage = parseInt(currentPage) - 1;
                if (dataRefineTab == "locations") {
                    lpPagination(currentPage);
                    locationData(currentPage);
                } else if (dataRefineTab == "products") {
                    lpPagination(currentPage);
                    productData(currentPage);
                }
            } else if (next) {
                currentPage = $(".pagination-item.active").text();
                currentPage = parseInt(currentPage) + 1;
                if (dataRefineTab == "locations") {
                    lpPagination(currentPage);
                    locationData(currentPage);
                } else if (dataRefineTab == "products") {
                    lpPagination(currentPage);
                    productData(currentPage);
                }
            } else {
                $(".pagination-item.active").removeClass("active");
                $(this).addClass("active");
                if (dataRefineTab == "locations") {
                    lpPagination();
                    locationData();
                } else if (dataRefineTab == "products") {
                    lpPagination();
                    productData();
                }
            }
        }
    });

    /**
     *  This function is used to manage the enabled & disabled pagination.
     *
     *  @param integer currentPage is the current page or selected pagination value
     *  
     */
    function lpPagination(currentPage) {
        $(".lp-content-wrapper .pagination-wrapper").show();
        $(".pagination-item").removeClass("js-disabled");
        pages = totalPages / perPage;

        if (Number(pages) === pages && pages % 1 !== 0) {
            pages = pages + 1;
        }

        if (currentPage === undefined || currentPage === "") {
            currentPage = $(".pagination-item.active").text();
        } else {
            currentPage = currentPage;
        }
        var paginationList = pagination(parseInt(currentPage), parseInt(pages));
        var selectedClass = "";
        $(".js-pagination").remove();
        if (paginationList.length > 0) {
            $.each(paginationList, function(index, value) {
                if ((currentPage === value) || (currentPage === value.toString())) {
                    selectedClass = "active";
                }
                if (isNaN(value)) {
                    $(".js-page-next").before("<li class=\"pagination-item js-pagination js-disabled \">" + value + "</li>");
                } else {
                    $(".js-page-next").before("<li class=\"pagination-item " + selectedClass + " js-pagination\">" + value + "</li>");
                }
                selectedClass = "";
            });
        } else {
            $(".js-page-next").before("<li class=\"pagination-item active js-pagination\">1</li>");
        }

        pages = parseInt(pages);
        if (pages === 1) {
            $(".js-page-prev").addClass("js-disabled");
            $(".js-page-next").addClass("js-disabled");
        } else if ((currentPage === 1) || currentPage === "1") {
            $(".js-page-prev").addClass("js-disabled");
        } else if ((currentPage === pages) || (currentPage === pages.toString())) {
            $(".js-page-next").addClass("js-disabled");
        }
    }

    /**
     *  This function is used to reset/clear right side of the container in location.
     *
     *  @param integer currentPage is the current page or selected pagination value
     *
     */
    function locationData(currentPage) {
        var activePage;
        if (currentPage === undefined || currentPage === "") {
            activePage = $(".pagination-item.active").text();
        } else {
            activePage = currentPage;
        }

        var currentPage = activePage - 1;

        $(".lp-content-wrapper .lp-corporate-list li").remove();
        $(".lp-content-wrapper .lp-branch-list li").remove();

        locationDataAll(currentPage, activePage);

    }

    /* Sanitize string values*/
    function escapeHtml(str) {
        return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
    }

    /**
     *  This function is used to load the location data.
     *
     *  @param integer currentPage is the current page or selected pagination value
     *  @param integer activePage is the one value reduced from currentPage
     *
     */
    function locationDataAll(currentPage, activePage) {
        var regionSelected, countrySelected;
        var corporateList = [];
        var branchList = [];
        var contactUsLabel = DOMPurify.sanitize($(".find-office-wrapper").attr("data-contact-us-label"));

        if (regionfirstdata != undefined) {
            regionSelected = regionfirstdata;
        } else {
            regionSelected = $(".region-dropdown .lp-dropdown-active-content").html();
            regionSelected = regionSelected.replace("&amp;", '&');
        }
        if (countryfirstdata != undefined) {
            countrySelected = countryfirstdata;
        } else {
            countrySelected = $(".country-dropdown .lp-dropdown-active-content").html();
        }

        for (var index = 0; index < locationRecords[refine][regionSelected][countrySelected].length; index++) {
            if (locationRecords[refine][regionSelected][countrySelected][index].officeType.toLowerCase() == "corporate") {
                corporateList.push(locationRecords[refine][regionSelected][countrySelected][index]);
            } else {
                branchList.push(locationRecords[refine][regionSelected][countrySelected][index]);
            }
        }

        for (var index = 0; index < branchList.length; index++) {
            corporateList.push(branchList[index]);
        }

        let corporateOfficeOutput = "";
        let branchOfficeOutput = "";
		for (var countryData = perPage * currentPage; countryData < perPage * (currentPage + 1); countryData++) {
            if(countryData >= corporateList.length) {
				break;
            }

            if(typeof corporateList[countryData] != 'undefined') {
				officeOutput = '<li><div class="lp-content"><div class="lp-content-container"><h4 class="lp-content-title">';

            officeOutput += corporateList[countryData]["officeName"];
			officeOutput += '</h4><div class="lp-detail-wrapper"><div class="lp-content-address">';

            officeOutput += '<span class="olam-text-p3">' + corporateList[countryData]["addressLine1"] + '</span>';
            officeOutput += '<span class="olam-text-p3">' + corporateList[countryData]["addressLine2"] + '</span>';
            officeOutput += '<span class="olam-text-p3">' + corporateList[countryData]["addressLine3"] + '</span>';

            officeOutput += '</div><div class="lp-contact-wrapper"><div class="lp-content-contact"><i class="icon-mail"></i><a class="olam-text-p4" href="#" data-toggle="modal" data-target="#contact_popup" data-email='+corporateList[countryData]["email"]+'>' + contactUsLabel + '</a></div>';

            if (corporateList[countryData]["phone"] != undefined && corporateList[countryData]["phone"] != "") {
                officeOutput += '<div class="lp-content-contact"><i class="icon-telephone"></i><a class="olam-text-p4" href="tel:' + corporateList[countryData]["phone"] + '">' + corporateList[countryData]["phone"] + '</a></div>';
            }
            // if (corporateList[countryData]["fax"] != undefined && corporateList[countryData]["fax"] != "") {
            //     officeOutput += '<div class="lp-content-contact g-pt-10 g-pt-xs-5 clearfix"><img class="img-responsive" src="/content/dam/olamgroup/icons/fax.png" alt="Fax"><a class="olam-text-p4" href="fax:' + corporateList[countryData]["fax"] + '">' + corporateList[countryData]["fax"] + '</a></div>';
            // }

            officeOutput += '</div></div></div>';
            officeOutput += '<div class="lp-content-map"><a href="' + corporateList[countryData]["mapUrl"] + '" target="_blank"  rel="noopener noreferrer" ><img class="img-responsive" src="' + ((corporateList[countryData]["imageUrl"] !== undefined && corporateList[countryData]["imageUrl"] !== "") ? corporateList[countryData]["imageUrl"] : "/content/dam/olamgroup/lp-map.JPG") + '" alt="map"></a></div></div></li>';
            if (window.innerWidth > 767) {
                if (activePage == 1) {
                    if (corporateList[countryData]["officeType"] == "Corporate") {
                        $(".lp-content-wrapper .lp-corporate > h4").show();
                        $(".lp-content-wrapper .lp-corporate-list").show();
                        corporateOfficeOutput += DOMPurify.sanitize(officeOutput);
                    }
                } else {
                    $(".lp-content-wrapper .lp-corporate > h4").hide();
                    $(".lp-content-wrapper .lp-corporate-list").hide();
                }
                if (corporateList[countryData]["officeType"] == "Branch") {
                    $(".lp-content-wrapper .lp-branch > h4").show();
                    branchOfficeOutput += DOMPurify.sanitize(officeOutput);
                }
            } else {
                if (corporateList[countryData]["officeType"] == "Corporate") {
                    $(".lp-content-wrapper .lp-corporate > h4").show();
                    $(".lp-content-wrapper .lp-corporate-list").show();
                    corporateOfficeOutput += DOMPurify.sanitize(officeOutput);
                }
                if (corporateList[countryData]["officeType"] == "Branch") {
                    $(".lp-content-wrapper .lp-branch > h4").show();
                    branchOfficeOutput += DOMPurify.sanitize(officeOutput);
                }
            }

           }    
		}
        document.querySelector(".lp-content-wrapper .lp-corporate-list").innerHTML = corporateOfficeOutput;
        document.querySelector(".lp-content-wrapper .lp-branch-list").innerHTML = branchOfficeOutput;
    }

    /**
     *  This function is used to reset/clear right side of the container in product
     *
     *  @param integer currentPage is the current page or selected pagination value
     *
     */
    function productData(currentPage) {
        var activePage;
        if (currentPage === undefined || currentPage === "") {
            activePage = $(".pagination-item.active").text();
        } else {
            activePage = currentPage;
        }

        var currentPage = activePage - 1;
        $(".lp-content-wrapper .lp-sales-list li").remove();
        productDataAll(currentPage, activePage);
    }

    /**
    *  This function is used to load the product data.
    *
    *  @param integer currentPage is the current page or selected pagination value
    *  @param integer activePage 
     *
    */
    function productDataAll(currentPage, activePage) {
        var productSelected = $(".product-dropdown .lp-dropdown-active-content").html();
        var salesList = [];
        var contactUsLabel = DOMPurify.sanitize($(".find-office-wrapper").attr("data-contact-us-label"));

        if(typeof productsRecords["products"][productSelected] != 'undefined') {
			 for (var index = 0; index < productsRecords["products"][productSelected].length; index++) {
                if (productsRecords["products"][productSelected][index].officeType.toLowerCase() == "") {
                    salesList.push(productsRecords["products"][productSelected][index]);
                }
            }
		}
        let productOfficeOutput = "";
        for (var productTypeData = perPage * currentPage; productTypeData < perPage * (currentPage + 1); productTypeData++) {
            if (salesList[productTypeData] !== undefined) {
                officeOutput = '<li><div class="lp-content"><div class="lp-content-container"><h4 class="lp-content-title">';
    
                officeOutput += salesList[productTypeData]["officeName"];
                officeOutput += '</h4><div class="lp-detail-wrapper">';
    
                if (salesList[productTypeData]["addressLine1"] != "" || salesList[productTypeData]["addressLine2"] != "" || salesList[productTypeData]["addressLine3"] != "") {
                    officeOutput += '<div class="lp-content-address">';
                    officeOutput += '<span class="olam-text-p3">' + salesList[productTypeData]["addressLine1"] + '</span>';
                    officeOutput += '<span class="olam-text-p3">' + salesList[productTypeData]["addressLine2"] + '</span>';
                    officeOutput += '<span class="olam-text-p3">' + salesList[productTypeData]["addressLine3"] + '</span>';
                    officeOutput += '</div><div class="lp-contact-wrapper">';
                } else {
                    officeOutput += '<div>';
                }
                
                officeOutput += '<div class="lp-content-contact"><i class="icon-mail"></i><a class="olam-text-p4" href="#" data-toggle="modal" data-target="#contact_popup" data-email='+ salesList[productTypeData]["email"]+'>' + contactUsLabel + '</a></div>';
    
                if (salesList[productTypeData]["phone"] != undefined && salesList[productTypeData]["phone"] != "") {
                    officeOutput += '<div class="lp-content-contact"><i class="icon-telephone"></i><a class="olam-text-p4" href="tel:' + salesList[productTypeData]["phone"] + '">' + salesList[productTypeData]["phone"] + '</a></div>';
                }
                // if (salesList[productTypeData]["fax"] != undefined && salesList[productTypeData]["fax"] != "") {
                //     officeOutput += '<div class="lp-content-contact g-pt-10 g-pt-xs-5 clearfix"><img class="img-responsive" src="/content/dam/olamgroup/icons/fax.png" alt="Fax"><a class="olam-text-p4" href="fax:' + salesList[productTypeData]["fax"] + '">' + salesList[productTypeData]["fax"] + '</a></div>';
                // }
                officeOutput += '</div></div></div>';
                officeOutput += '<div class="lp-content-map"><a href="' + ((salesList[productTypeData]["mapUrl"] != "") ?  salesList[productTypeData]["mapUrl"] : "javascript:void(0);")  + '" target="_blank"  rel="noopener noreferrer" ><img class="img-responsive" src="' + ((salesList[productTypeData]["imageUrl"] !== undefined && salesList[productTypeData]["imageUrl"] !== "") ? salesList[productTypeData]["imageUrl"] : "/content/dam/olamgroup/lp-map.JPG")  + '" alt="map"></a></div></div></li>';
    
                if (salesList[productTypeData]["officeType"] == "") {
                    $(".lp-content-wrapper .lp-sales").show();
                    $(".lp-content-wrapper .lp-sales > h4").show();
                    $(".lp-content-wrapper .lp-sales-list").show();
                    productOfficeOutput += DOMPurify.sanitize(officeOutput);
                }
            }
        }
        document.querySelector(".lp-content-wrapper .lp-sales-list").innerHTML = productOfficeOutput;
    }


    /**
     *  This function is used to load the data based on the tab selection
     *
     *  @param string regionSelected is the selected region value
     *  @param string countrySelected is the selected country value
     *
     */
    function loctaionsDataLoad(regionSelected, countrySelected) {
        if ($("#contact-myTab").is(":visible")) {
            totalPages = locationRecords["locations"][regionSelected][countrySelected].length;
            locationTotalPaginationPages = totalPages;

            $(".lp-content-wrapper .lp-corporate > h4").hide();
            $(".lp-content-wrapper .lp-branch > h4").hide();
            $(".lp-content-wrapper .lp-corporate-list li, .lp-content-wrapper .lp-branch-list li").remove();
            if (window.innerWidth > 767) {
                lpPagination(currentPage);
                locationData();
            } else {
                locationLoadmoreCount = 0;
                productLoadmoreCount = 0;
                $('.lp-content-wrapper .loadmore-wrapper').hide();
            }
        }
    }

    /**
     *  This event is used load the product/location data based on the dropdown selection
     *
     */
    $(document).on('click', '.lp-dropdown-data a', function() {
        let clickEvent = $(this).parents(".lp-dropdown").attr("name");
        let compName = $(this).parents(".find-office-wrapper").attr("data-component");
        /*
        $(this).parents('.lp-dropdown-content').prev().find('.lp-dropdown-active-content').html($(this).html());
        $(this).parents('.lp-dropdown-content').slideToggle();
        $(this).parents('.lp-dropdown-content').prev().find('.glyphicon').toggleClass('glyphicon-menu-down glyphicon-menu-up');
        */

        if ($(this).parents().hasClass("contact-refine")) {
            if ($(this).parents('.lp-dropdown').hasClass("region-dropdown")) {
                $(".country-dropdown .lp-dropdown-active-content").html("Select a country");
                $("#home1").find(".country-dropdown ul").children('li').remove();
                var regionSelected = $(this).html();
                
                regionSelected = regionSelected.replace("&amp;", '&');
                if (locationRecords[refine][regionSelected]) {
                    for (var countryData in locationRecords[refine][regionSelected]) {
                        $("#home1").find(".country-dropdown ul").append("<li><a href='javascript:void(0);' class=' contact-country'>" + countryData + "</a></li>");
                    }
                }
                let filterObject = [
                    {
                        "filterType": "Refine",
                        "filterValue": "Locations"
                    },
                    {
                        "filterType": "Region",
                        "filterValue": (regionSelected != undefined ? regionSelected : "")
                    },
                    {
                        "filterType": "Country",
                        "filterValue": (countrySelected != undefined ? countrySelected : "")
                    }
                ]
                    analyticsNewsFilterTracking(filterObject, clickEvent, compName);
            }

            if ($(this).parents('.lp-dropdown').hasClass("country-dropdown")) {
                var regionSelected = $(".region-dropdown .lp-dropdown-active-content").html();
                regionSelected = regionSelected.replace("&amp;", '&');
                var countrySelected = $(".country-dropdown .lp-dropdown-active-content").html();
                regionfirstdata = undefined;
                countryfirstdata = undefined;
                loctaionsDataLoad(regionSelected, countrySelected);
                let filterObject = [
                    {
                        "filterType": "Refine",
                        "filterValue": "Locations"
                    },
                    {
                        "filterType": "Region",
                        "filterValue": (regionSelected != undefined ? regionSelected : "")
                    },
                    {
                        "filterType": "Country",
                        "filterValue": (countrySelected != undefined ? countrySelected : "")
                    }
                ]
                    analyticsNewsFilterTracking(filterObject, clickEvent, compName);
            }

            if ($(this).parents('.lp-dropdown').hasClass("product-dropdown")) {
                var productSelected = $(this).html();
                var productSalesCount = 0;
                for (var productSales in productsRecords["products"][productSelected]) {
                    if (productsRecords["products"][productSelected][productSales]["officeType"] == "") {
                        productSalesCount++;
                    }
                }
                totalPages = productSalesCount;
                productTotalPages = totalPages;
                if (window.innerWidth > 767) {
                    lpPagination(currentPage);
                    productData();
                } else {
                    $(".lp-content-wrapper .lp-sales > h4").hide();
                    $(".lp-content-wrapper .lp-sales-list li").remove();
                    locationLoadmoreCount = 0;
                    productLoadmoreCount = 0;
                    $('.lp-content-wrapper .loadmore-wrapper').hide();
                }
                let filterObject = [
                    {
                        "filterType": "Refine",
                        "filterValue": "Products"
                    },
                    {
                        "filterType": "Product",
                        "filterValue": (productSelected != undefined ? productSelected : "")
                    }
                ]
                    analyticsNewsFilterTracking(filterObject, clickEvent, compName);
            }
        }
    });
    /* Location Product Tab Functionality End */

    /* Location Product Tab Click Start */
    /**
     *  This event is used load the product/location data in right side, based on the dropdown selection.
     *
     */
    $(document).on('click', '.contact-refine .nav-link', function() {
        let clickEvent = $(this).closest("a").attr("data-refine");
        let compName = $(this).parents(".find-office-wrapper").attr("data-component");
        dataRefineTab = $(this).attr("data-refine");
        let reginSelectVal = $(".region-dropdown .lp-dropdown-active-content").text();
        let countrySelectVal = $(".country-dropdown .lp-dropdown-active-content").text();
        dataRefineTab = $(this).attr("data-refine");
        if (dataRefineTab == 'locations') {
            $(".lp-sales").hide();
            $(".lp-corporate").show();
            $(".lp-branch").show();
            if (($(".region-dropdown .lp-dropdown-active-content").html() != "Select a region" && $(".country-dropdown .lp-dropdown-active-content").html() != "Select a country") || (regionfirstdata != undefined && countryfirstdata != undefined)) {
                if (window.innerWidth > 767) {
                    $(".pagination-wrapper").show();
                    if (locationTotalPaginationPages > 0) {
                        totalPages = locationTotalPaginationPages;
                    }
                    currentPage = 1;
                    lpPagination(currentPage);
                    locationData();
                } else {
                    if (locationTotalPaginationPages > (perPage * (locationLoadmoreCount + 1))) {
                        $(".lp-content-wrapper .loadmore-wrapper").show();
                    } else {
                        $(".lp-content-wrapper .loadmore-wrapper").hide();
                    }
                }
            } else {
                $(".pagination-wrapper").hide();
                $('.lp-content-wrapper .loadmore-wrapper').hide();
            }
            let filterObject = [
                {
                    "filterType": "Refine",
                    "filterValue": dataRefineTab
                },
                {
                    "filterType": "Region",
                    "filterValue": (reginSelectVal == "Select a region" ? "" : reginSelectVal)
                },
                {
                    "filterType": "Country",
                    "filterValue": (countrySelectVal = "Select a Country" ? "" : countrySelectVal)
                }
            ]
                analyticsNewsFilterTracking(filterObject, clickEvent, compName);


        } else if (dataRefineTab == 'products') {
            let productSelectVal = $(".product-dropdown .lp-dropdown-active-content").text();
            $(".lp-corporate").hide();
            $(".lp-branch").hide();
            $(".lp-sales").show();
            if ($(".product-dropdown .lp-dropdown-active-content").html() != "Select a product") {
                if (window.innerWidth > 767) {
                    $(".pagination-wrapper").show();
                    if (productTotalPages > 0) {
                        totalPages = productTotalPages;
                    }
                    currentPage = 1;
                    lpPagination(currentPage);
                    productData();
                } else {
                    if (productTotalPages > (perPage * (productLoadmoreCount + 1))) {
                        $(".lp-content-wrapper .loadmore-wrapper").show();
                    } else {
                        $(".lp-content-wrapper .loadmore-wrapper").hide();
                    }
                }
            } else {
                $(".pagination-wrapper").hide();
                $('.lp-content-wrapper .loadmore-wrapper').hide();
            }
            let filterObject = [
                    {
                        "filterType": "Refine",
                        "filterValue": "Products"
                    },
                    {
                        "filterType": "Product",
                        "filterValue": (productSelectVal == "Select a product" ? "" : productSelectVal)
                    }
                ]
                    analyticsNewsFilterTracking(filterObject, clickEvent, compName);
        }
    });
    /* Location Product Tab Click End */

    /* Location Product Load More Click Start */
    /**
     *  This event is used load more data of product/location data in right side
     *
     */
    var locationLoadmoreCount = 0;
    var productLoadmoreCount = 0;
    $(document).on('click', '.lp-loadmore,.locationUpdate,.productUpdate', function() {
        perPage = 3;
        if (dataRefineTab == 'locations') {
            if (locationTotalPaginationPages > (perPage * (locationLoadmoreCount + 1))) {
                $(".lp-content-wrapper .loadmore-wrapper").show();
            } else {
                $(".lp-content-wrapper .loadmore-wrapper").hide();
            }
            locationDataAll(locationLoadmoreCount);
            locationLoadmoreCount++;
        }
        if (dataRefineTab == 'products') {
            if (productTotalPages > (perPage * (productLoadmoreCount + 1))) {
                $(".lp-content-wrapper .loadmore-wrapper").show();
            } else {
                $(".lp-content-wrapper .loadmore-wrapper").hide();
            }
            productDataAll(productLoadmoreCount);
            productLoadmoreCount++;
        }
    });
    /* Location Product Load More Click End */
});
function isElementVisible(el) {
    return (el.offsetParent !== null)
}

function renderSameSizeButton(isFromPopup) {
    const sameSizeBtnWrapper = isFromPopup ? document.querySelectorAll(".modal .same-size-button__wrapper") : 
    document.querySelectorAll("div:not(.modal) .same-size-button__wrapper");
    for (const element of sameSizeBtnWrapper) {
        if (isElementVisible(element)) {
            const btnSection = element.querySelectorAll(".primary-button, .secondary-button");
            const btnWidthList = [];
            if (btnSection.length > 1) {
                for (const btn of btnSection) {
                    let btnWidth = isFromPopup ? btn.clientWidth : btn.getBoundingClientRect().width;
                    btnWidthList.push(btnWidth);
                }
                const btnMaxWidth = Math.max(...btnWidthList);
                for (const btn of btnSection) {
                    btn.style.width = btnMaxWidth + "px";
                }
            }
        }
    }
}

$(window).load(function() {
    const isFromPopup = false;
    renderSameSizeButton(isFromPopup);
});

$('.modal').on('shown.bs.modal', function() {
    const isFromPopup = true;
    renderSameSizeButton(isFromPopup);
});
function onYouTubePlayerAPIReady() {
    $('.olam-video').each(function () {
        let videoPlayer = $(this).find('.olam-video__frame');
        let playerId = $(videoPlayer).attr('id');
        let videoPoster = $(this).find('.olam-video__poster');
        let buttonWrapper = $(this).find('.olam-video__btn-container');
        const enableVideoPosterToggle = $(this).hasClass('js-video-player-toggle-poster');
        if (videoPlayer && playerId) {
            new YT.Player(playerId, {
                events: {
                    onReady: function (ev) {
                        $(buttonWrapper).on('click', function () {
                            $(videoPoster).hide();
                            $(videoPlayer).show();
                            ev.target.playVideo();
                        });

                    },
                    onStateChange: enableVideoPosterToggle && function (event) {
                        if (
                            event.data == YT.PlayerState.PAUSED ||
                            event.data == YT.PlayerState.ENDED
                        ) {

                            $(videoPoster).show();
                            $(videoPlayer).hide();
                        } else if (event.data == YT.PlayerState.PLAYING) {
                            $(videoPoster).hide();
                            $(videoPlayer).show();
                        }
                    }
                }
            });
        }
    });
}

window.onload = (event) => {
    var tag = document.createElement("script");
    tag.src = "https://www.youtube.com/player_api";
    var firstScriptTag = document.getElementsByTagName("script")[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}
(function () {
    const requestAnimationFrame = window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    function (callback) {
        window.setTimeout(callback, 1000 / 60)
    }

    function isInViewport(el) {
        const rect = el.getBoundingClientRect();
        const windowHeight = (window.innerHeight || document.documentElement.clientHeight);
        const windowWidth = (window.innerWidth || document.documentElement.clientWidth);

        const vertInView = (rect.top <= windowHeight) && ((rect.top + rect.height) >= 0);
        const horInView = (rect.left <= windowWidth) && ((rect.left + rect.width) >= 0);

        return (vertInView && horInView);
    }

    const Animation = function() {
        this.initialScrollY = window.scrollY;
        this.scrollThreshold = -1;
    }

    Animation.prototype = {
        init() {
            this.animationList = document.querySelectorAll("[data-animate='true']");
            this.animationList.length && this.updateAnimation();
        },
        updateAnimation() {
            const currentScrollY = window.scrollY;
            if (Math.abs(this.initialScrollY - currentScrollY) > this.scrollThreshold) {
                this.animationList.forEach((element) => {
                    const animationStyle = element.dataset.animation;
                    const animationDuration = element.dataset.animationDuration;
                    const animationDelay = element.dataset.animationDelay;
                    if (isInViewport(element)) {
                        element.classList.add(animationStyle);
                        if (animationDuration) element.style.animationDuration = animationDuration;
                        if (animationDelay) element.style.animationDelay = animationDelay;
                    } else {
                        element.classList.remove(animationStyle);
                        element.removeAttribute("style");
                    }
                });
                this.initialScrollY = currentScrollY;
            }
    
            requestAnimationFrame(this.updateAnimation.bind(this));
        }
    }

    window.addEventListener('load', (event) => {
        const animate = new Animation();
        animate.init();
    });
})();
(function () {
    $(".olam-faq-content-item-question-container").on("click", function () {
        var currentBoolean = $(this).next().is(':hidden');
        var accordion = $(".olam-faq-content-item-question-container");

        $.each(accordion, function (key, value) {
            $(this).next().hide();
            $(this).find(".olam-faq-content-item-answer").addClass("olam-faq-content-item-answer-collapsed");
            $(this).find(".olam-faq-content-item-arrow > i").removeClass("fa-chevron-up").addClass("fa-chevron-down");
        });
        if (currentBoolean) {
            $(this).next().show();
            $(this).find(".olam-faq-content-item-answer").removeClass("olam-faq-content-item-answer-collapsed");
            $(this).find(".olam-faq-content-item-arrow > i").addClass("fa-chevron-up").removeClass("fa-chevron-down");
        } else {
            $(this).next().hide();
            $(this).find(".olam-faq-content-item-answer").addClass("olam-faq-content-item-answer-collapsed");
            $(this).find(".olam-faq-content-item-arrow > i").removeClass("fa-chevron-up").addClass("fa-chevron-down");
        }
    });
})();
(function () {
    const requestAnimationFrame = window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame || 
    function (callback) {
        window.setTimeout(callback, 1000 / 60)
    }
    
    const cancelAnimationFrame = window.cancelAnimationFrame ||
    window.webkitRequestCancelAnimationFrame ||
    window.mozCancelAnimationFrame || 
    function (callback) {
        window.setTimeout(callback, 1000 / 60)
    }

    initiateAnimation = false;
    let container = document.querySelector(".olam-impact-container");
    let elementList = document.querySelectorAll(".olam-impact-number-item");
    let animationDuration = 3000;
    let initialValue = 0;

    document.addEventListener('scroll', (e) => {
        if(container && isInViewport(container) && !initiateAnimation) {
            initiateAnimation = true;
            console.info("elementList", elementList);
            if(elementList.length > 0) {
                elementList.forEach((element) => {
                    let elementInnerVal = element.innerHTML;
                    if(elementInnerVal.length > 0) {
                        let finalVal = elementInnerVal.match(/\d+(\,\d+)+|\d+(\.\d+)+|\d+/g)
                        let splittedString = elementInnerVal.replace(finalVal, "")

                        animateNumber(element, initialValue, parseFloat(finalVal[0].replace(/,/g, '')), animationDuration, elementInnerVal, splittedString)
                    }
                });
            }
        }
    });


    function animateNumber(obj, initVal, finalVal, duration, elementInnerVal, splittedString) {
        console.log("obj", obj, initVal, finalVal, duration, elementInnerVal, splittedString);
        let startTime = null;

        //get the current timestamp and assign it to the currentTime variable
        let currentTime = Date.now();

        //pass the current timestamp to the step function
        const step = (currentTime) => {
            //if the start time is null, assign the current time to startTime
            if (!startTime) {
                startTime = currentTime;
            }

            //calculate the value to be used in calculating the number to be displayed
            const progress = Math.min((currentTime - startTime) / duration, 1);

            //calculate what to be displayed using the value gotten above            
            obj.innerHTML = numberWithCommas(Math.floor(progress * (finalVal - initVal) + initVal)) + splittedString;

            //checking to make sure the counter does not exceed the last value (finalVal)
            if (progress < 1) {
                requestAnimationFrame(step);
            } else {
                obj.innerHTML = elementInnerVal;
                cancelAnimationFrame(requestAnimationFrame(step));
            }
        };

        //start animating
        requestAnimationFrame(step);
    }

    function numberWithCommas(val) { return val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); }

    function isInViewport(el) {
        const rect = el.getBoundingClientRect();
        const windowHeight = (window.innerHeight || document.documentElement.clientHeight);
        const windowWidth = (window.innerWidth || document.documentElement.clientWidth);

        const vertInView = (rect.top <= windowHeight) && ((rect.top + rect.height) >= 0);
        const horInView = (rect.left <= windowWidth) && ((rect.left + rect.width) >= 0);

        return (vertInView && horInView);
    }

})();