const PullDown = function(nav, icon) {
    const menu = document.querySelector(nav);
    const pull = document.querySelector(icon);
    let isInit = false;
    const body = document.body;

    function toggleMenu(e) {
        e.preventDefault();

        if (menu.offsetHeight != 0) {
            body.classList.remove("menu-open");

            TweenMax.to(menu, 0.2, {
                height: 0,
                autoAlpha: 0, 
                ease: Back.easeIn
            });

        } else {
            body.classList.add("menu-open");

            TweenMax.set(menu, {
                height: "auto",
                autoAlpha: 1
            });

            TweenMax.from(menu, 0.45, {
                height: 0,
                autoAlpha: 0,
                ease: Back.easeOut
            });
        }
    }

    function triggerMenu() {
        if (window.innerWidth < 769 && !isInit) {
            isInit = !isInit;
            if (menu.className == "secondary-nav") menu.style.display = "block";
            TweenLite.set(menu, {
                height: 0,
                autoAlpha: 0
            });
            pull.addEventListener("click", toggleMenu);
        } else if (window.innerWidth > 769 && isInit) {
            isInit = !isInit;
            if (menu.className == "secondary-nav") menu.style.display = "flex";
            TweenLite.set(menu, {
                height: "auto",
                autoAlpha: 1
            });
            pull.removeEventListener("click", toggleMenu);
        }
    }

    window.addEventListener("resize", triggerMenu);
    triggerMenu();
};

let mainPullDown = new PullDown(".nav", ".nav-pull");
let subnavPullDown = new PullDown(".sub-nav", ".sub-nav-pull");

const contentPullDown = function (parent, child) {
    const className = `${child}--show`.replace(".", "");
    const _parent = document.querySelector(parent);
    if (!_parent) return;

    _parent.addEventListener("click", function (e) {
        e.preventDefault();
        const _child = document.querySelector(child);
        _child.classList.toggle(className);
    });
}

const zIndexSwipe = function (trigger, content) {

    const _trigger = document.querySelector(trigger);
    const _content = document.querySelector(content);
    const body = document.querySelector("body");
    
    _trigger.addEventListener("click", function (e) {
        e.preventDefault();
        let currentZIndex = body.dataset.zindex;
        _content.style.zIndex = currentZIndex++;
        body.dataset.zindex = currentZIndex;

    });
}

let secondaryNavItemPullDown = new contentPullDown(".secondary-link-popup__popup", ".secondary-flyout");

//if (document.querySelector('.secondary-nav')) {
if (document.querySelector(".secondary-pull")) {
    //let secondaryPullDown = new PullDown(".secondary-nav", ".secondary-pull");
    $(".secondary-pull").click(function () {
        var el = $(".secondary-nav")[0];

        if (el.className.indexOf("secondary-nav-mobile-full-height") !== -1) {
            el.className = el.className.replace("secondary-nav-mobile-full-height", "");
        } else {
            el.className += " secondary-nav-mobile-full-height";
        }

        var icons = this.querySelectorAll(".icon");
        for (var i = 0; i < icons.length; i++) {
            var icon = icons[i];
            if (icon.style.opacity !== "0") {
                icon.style.opacity = "0";
            } else {
                icon.style.opacity = "1";
            }
        }

    });


    let secondaryLinkPullDown = new contentPullDown(".secondary-nav-item__sub", ".secondary-sub");
    /*let zIndexSwipeFlyout = new zIndexSwipe(".secondary-link-popup__popup", ".secondary-flyout");*/
    /*let zIndexSwipeSecondary = new zIndexSwipe(".secondary-pull", ".secondary-nav");*/
} 

if (document.querySelector(".header")) {
    //scroll add fixed class
    var stickyNavTop = $(".header").offset().top;

    var stickyNav = function () {
        const scrollTop = $(window).scrollTop(); // our current vertical position from the top

        if (scrollTop > stickyNavTop) {
            $("body").addClass("fixed-header");
        } else {
            $("body").removeClass("fixed-header");
        }
    };
    stickyNav();

    $(window).scroll(function () {
        stickyNav();
    });
}

// call popup loading script
$(function () {
    $("#salesOffices").change(function () {
        const option = $(this).find("option").eq($(this).prop("selectedIndex"));

        $(".call_selected_title").html($(this).val());
        $(".call_selected_title").siblings(".call_selected_link").remove();
        const phoneNumbers = option.data("phone").split("<br/>");
        var phoneHtml = "";
        $.each(phoneNumbers, function (index, value) {
            phoneHtml += ` <a class="call__link call_selected_link" href="tel:${value}">${value}</a>`;
        });
        $(".call_selected_title").after(phoneHtml);
        //$(".call_selected_address").html(option.data("address"));
    });

    $("#salesOffices").change();
});;
const StaticMap = function(element, options) {
    const el = document.querySelector(element);

    const win = window.location.origin.indexOf("glhomes.com") === -1
        ? "https://www.glhomes.com"
        : window.location.origin;

    const baseUrl = "https://maps.googleapis.com/maps/api/staticmap";
    const settings = {
        latLng: el.dataset.location || "0,0",
        link: el.dataset.link || null,
        zoom: 14,
        size: "500x250",
        icon: `${win}${el.dataset.marker || ""}`,
        key: el.dataset.apikey
    }; 
     
    init();
     
    function init() {
        Object.assign(settings, options || {});
        
        const img = document.createElement("img");
        img.src = buildStaticMap();

        // embed image in a link if specified
        if (settings.link) {
            const link = document.createElement("a");
            link.href = settings.link;
            link.target = "_blank";

            link.append(img);
            el.prepend(link);
        }
        else
            el.prepend(img);
    }

    function buildStaticMap() {
        const url = `${baseUrl}?center=${settings.latLng}&zoom=${settings.zoom}&size=${settings.size}` +
                    `&markers=icon:${settings.icon}|${settings.latLng}&style=feature:poi|visibility:off&key=${settings.key}`;
        return encodeURI(url);
    }
};
;
(function ($) {
    // ReSharper disable once InconsistentNaming
    class Popup {
        constructor(element) {
            // get settings from data tags
            this.id = element.data("popupid");
            this.name = element.data("popupname");
            this.preview = element.hasClass("preview");
            this.delay = parseInt(element.data("delay"));
            this.showAgain = element.data("showagain") === true;
            this.showAgainDelay = parseInt(element.data("showagaindelay"));
            this.closeAfterForm = element.data("closeafterform") === true;
            this.closeAfterFormDelay = parseInt(element.data("closeafterformdelay"));

            // get dom instances
            this.element = element;
            this.closer = element.find(".popup-close > i, .popup-close > img, .popup-close > svg");
            this.splash = element.find(".popup-splash");
            this.splashShowContent = this.splash.hasClass("showcontent");
            this.showBoldChat = this.splash.hasClass("splashBoldChat");
            this.content = element.find(".popup-content");

            // additional operational settings
            this.closed = false;
            this.shown = false;
            this.contentShown = false;
            this.contentCompleted = false;

            if (!this.splashShowContent && this.content.length) {
                this.content.show();
            }
            // attach handler to splash toggle if necessary
            else if (this.splashShowContent && this.content.length && this.showBoldChat === false) {
                this.splash.click(() => { this.switchToContent(); });
            }
            else if (this.splashShowContent && this.content.length && this.showBoldChat) {
                this.splash.click(() => { this.hide(true); });
            }


            // if splash image is a link, track as a completion
            if (this.splash && this.splash.length && this.splash.is("a")) {
                this.splash.click(() => { this.trackEvent("popupCompleted"); });
            }
        }

        show() {
            // if already previously shown, prevent future re-shows
            if (this.shown && this.showAgain) {
                this.showAgain = false;
            }

            this.element.addClass("shown");
            this.shown = true;
            this.trackEvent("popupShown");
        }

        hide(closedByUser) {
            this.element.removeClass("shown");
            if (closedByUser) {
                this.closed = true;

                // track that the user closed it without completing
                if (!this.contentCompleted) {
                    this.trackEvent("popupClosed");
                }

                if (this.contentShown && this.splash && this.splash.length)
                    this.switchBackToSplash();
            }
        }

        switchToContent() {
            this.splash.hide();
            this.content.show();
            this.contentShown = true;
            this.trackEvent("popupClicked");
        }

        switchBackToSplash() {
            this.splash.show();
            this.content.hide();
            this.contentShown = false;
        }

        trackEvent(eventName) {
            if (window.dataLayer === undefined || window.dataLayer === null) return;

            // ignore tracking when in the CMS
            const url = window.location.pathname;
            if (url && url.toLowerCase().indexOf("/episerver/cms") > -1) return;

            const data = {
                "event": eventName,
                "popupType": this.name,
                "pageUrl": url
            };
            window.dataLayer.push(data);
            console.log(JSON.stringify(data));
        }
    }

    // ReSharper disable once InconsistentNaming
    class CookieManager {
        setValue(name, value, days) {
            let expires = "";
            if (days) {
                const date = this.calcDaysFromNow(days);
                expires = `; expires=${date.toUTCString()}`;
            }
            document.cookie = name + "=" + (value || "") + expires + "; path=/";
        }

        getValue(name) {
            const nameEq = name + "=";
            const ca = document.cookie.split(";");
            for (let i = 0; i < ca.length; i++) {
                let c = ca[i];
                while (c.charAt(0) === " ") c = c.substring(1, c.length);
                if (c.indexOf(nameEq) === 0) return c.substring(nameEq.length, c.length);
            }
            return null;
        }

        remove(name) {
            document.cookie = `${name}=; Max-Age=-99999999;`;
        }

        calcDaysFromNow(days) {
            const date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            return date;
        }
    }

    // ReSharper disable once InconsistentNaming
    class PopupManager {
        constructor() {
            this.closeLimit = 2;
            this.stateTimeoutDays = 0.5; // 12 hours
            this.completedTimeoutDays = 365; // 1 year
            this.cookies = new CookieManager();

            this.instances = [];
            this.pendingOpen = [];
            this.openInstance = null;
            this.timer = null;
            this.closeAfterFormSubmitTimer = null;

            window.addEventListener('hashchange', () => {
                this.hashChange();
            });
        }

        register(el) {

            if (this.isOpenedByButtonClick(el))
                return;

            const instance = new Popup($(el));
            this.instances.push(instance);

            // register handlers for user events
            instance.closer.click(() => { this.onClosedByUser(instance); });

            // detect form instances in content area
            const contentForms = instance.content.find(".EPiServerForms");
            contentForms.each((i, e) => {
                this.listenForFormSubmit(e, instance);
            });

            // add it to the queue to be tested
            this.pendingOpen.push(instance);

            // start queue processing if not already
            this.start();
        }

        isOpenedByButtonClick(element) {
            const parent = $(element).parent(".popup-button-click");
            return parent.length > 0;
        }

        hashChange() {
            var hash = window.location.hash;
            if (hash) {
                hash = hash.replace(/-/g, '').replace(/#/g, '');
                for (let instance of this.instances) {
                    if (hash === instance.id) {
                        window.location.hash = '';
                        this.show(instance);
                        break;
                    }
                }
            }
        }

        start() {
            if (this.timer) return; // ignore if already started

            // process immediately
            this.processQueue();

            // run on timer after first run
            this.timer = window.setInterval(() => { this.processQueue(); }, 1000);
        }

        stop() {
            if (!this.timer) return;
            window.clearInterval(this.timer);
            this.timer = null;
        }

        listenForFormSubmit(e, instance) {
            // make sure we have something to listen with
            if (!e || !e.length || !$$epiforms || !instance) return;

            // find the unique ID of the form element
            const formId = `#${e.id}`;

            $$epiforms(formId).on("formsSubmitted", (event) => {
                // make sure form succeeded and the data layer is already initialized
                if (!event.isFinalizedSubmission || !event.isSuccess) return;

                // make sure it was the open instance that was closed
                if (instance !== this.openInstance) return;

                // make sure it doesn't accidentally show again if user closes it
                // before the close timer goes off to close it. 
                instance.showAgain = false;
                instance.contentCompleted = true;
                instance.trackEvent("popupCompleted");
                this.storePopupWasCompleted(instance); // remember in a cookie

                if (instance.closeAfterForm) {

                    // form was submitted, schedule to close the popup
                    if (instance.closeAfterFormDelay <= 0) {
                        this.hide(false);
                    } else {
                        this.closeAfterFormSubmitTimer = window.setTimeout(() => {
                            this.hide(false);
                        }, instance.closeAfterFormDelay * 1000);
                    }
                }

                if (instance.afterformSubmitted && typeof (instance.afterformSubmitted) === "function")
                    instance.afterformSubmitted();

            });
        }

        processQueue() {
            // before anything test for live chat window state
            const liveChatOpen = this.isLiveChatOpen();

            // if live chat opened and we have a popup open, close it
            if (liveChatOpen && this.openInstance) {
                const instance = this.openInstance;
                this.hide(); // hide it immediately

                // add it to front of pending list to show after live chat closes
                this.pendingOpen.unshift(instance);
                return;
            }

            // continue waiting until live chat is not open
            if (liveChatOpen) return;

            // make sure there are any due to be opened yet
            if (!this.pendingOpen || !this.pendingOpen.length) return;

            // loop thru all pending and open first that can be opened
            let index = -1;
            for (let pending of this.pendingOpen) {
                index++;

                // skip any that cant be opened yet
                if (!this.canOpenPopup(pending)) continue;

                // this can be opened, remove from pending and show it
                this.pendingOpen.splice(index, 1);
                this.show(pending);
                break;
            }
        }

        show(instance) {
            if (this.openInstance) return;
            instance.show();
            this.openInstance = instance;
        }

        hide(closedByUser) {
            if (!this.openInstance) return;

            // clear any close timer that is running
            if (this.closeAfterFormSubmitTimer) {
                window.clearTimeout(this.closeAfterFormSubmitTimer);
                this.closeAfterFormSubmitTimer = null;
            }

            const instance = this.openInstance;
            instance.hide(closedByUser);
            this.openInstance = null;

            if (closedByUser) {
                const state = this.getPopupClosedState(instance);
                state.occurrence++; // increment close count

                // choose the delay based on settings and number of times closed
                const delayUntilDays = instance.showAgain && state.occurrence === 1
                    ? this.secondsToDays(instance.showAgainDelay) // for show again the user decides the delay in seconds
                    : this.stateTimeoutDays; // otherwise we use the default delay of 12 hours

                // update the delay and store the state for this popup
                state.delayUntil = this.cookies.calcDaysFromNow(delayUntilDays);
                this.storePopupClosedState(instance, state);

                // add it back to the list to monitor
                this.pendingOpen.push(instance);
            }
        }

        canOpenPopup(instance) {
            if (instance.preview) return true; // always show in preview

            // check if the popup was completed
            if (this.getPopupWasCompleted(instance)) return false;

            // check if there is close state for this popup
            const closeState = this.getPopupClosedState(instance);

            // if its been closed more than the limit don't show it
            if (closeState.occurrence >= this.closeLimit) return false;

            // check if there is a delay that has not passed yet
            return closeState.delayUntil === null || new Date() >= closeState.delayUntil;
        }

        getPopupClosedState(instance) {
            const key = this.getCloseStateTrackingKey(instance);
            const stateString = this.cookies.getValue(key);
            if (stateString) {
                try {
                    const parsed = JSON.parse(stateString);
                    if (parsed.delayUntil !== null)
                        parsed.delayUntil = new Date(parsed.delayUntil);
                    return parsed;
                } catch (e) {
                    console.log(`Unable to parse popup state: ${e}`);
                }
            }

            // since we have to create the default state, use the delay 
            // setting from the popup for the the initial delay time
            const delayUntil = this.cookies.calcDaysFromNow(this.secondsToDays(instance.delay));

            // use default state if there was none or failed to deserialize
            const state = { occurrence: 0, delayUntil: delayUntil };
            this.storePopupClosedState(instance, state);
            return state;
        }

        storePopupClosedState(instance, state) {
            const key = this.getCloseStateTrackingKey(instance);
            const stateString = JSON.stringify(state);
            this.cookies.setValue(key, stateString, this.stateTimeoutDays);
        }

        getPopupWasCompleted(instance) {
            const key = this.getCompletedTrackingKey(instance);
            return this.cookies.getValue(key) === "1";
        }

        storePopupWasCompleted(instance) {
            const key = this.getCompletedTrackingKey(instance);
            this.cookies.setValue(key, "1");
        }

        getCloseStateTrackingKey(instance) {
            return `${instance.id}:state`;
        }

        getCompletedTrackingKey(instance) {
            return `${instance.id}:completed`;
        }

        onClosedByUser(instance) {
            if (instance !== this.openInstance) return;
            this.hide(true);
        }

        isLiveChatOpen() {
            // ReSharper disable PossiblyUnassignedProperty
            return window.bcChatWindows && window.bcChatWindows.length > 0;
            // ReSharper enable PossiblyUnassignedProperty
        }

        secondsToDays(value) {
            if (value === 0) return 0;
            return value / (60 * 60 * 24);
        }
    }

    // load manager and popups
    const manager = new PopupManager();

    // add all popups to the manager
    const popups = $(".popup");
    popups.each((i, o) => {
        manager.register(o);
    });

    class PopupButton {
        static start() {
            const instatnce = new PopupButton();
            instatnce.initialize();
        }

        initialize() {
            const buttons = document.querySelectorAll(".btn-popup");

            for (const button of buttons) {
                const popup = $(`#${button.dataset.popupId}`);

                const onFormSubmmtionEvent = function () {
                    button.style.display = "none";
                }

                button.addEventListener('click', (e) => {
                    e.preventDefault();
                    this.create(popup, onFormSubmmtionEvent);
                });
            }
        }

        create(element, formSubmmtionEvent) {
            const manager = new PopupManager();
            const instance = new Popup(element);

            if (formSubmmtionEvent)
                instance.afterformSubmitted = formSubmmtionEvent;

            const contentForms = instance.content.find(".EPiServerForms");
            contentForms.each((i, e) => {
                manager.listenForFormSubmit(e, instance);
            });
            manager.openInstance = instance;
            instance.closer.click(() => { manager.onClosedByUser(instance); });
            instance.show();
        }
    }

    PopupButton.start();

})($);

class AddressAutoFill {

    static create(form) {
        return new AddressAutoFill(form)
    }

    constructor(form) {

        this.componentForm = {
            street_number: "short_name",
            route: "long_name",
            locality: "long_name",
            administrative_area_level_1: "short_name",
            administrative_area_level_2: "long_name",
            country: "long_name",
            postal_code: "short_name",
        };

        this.formMap = {
            street_number: "streetNumber",
            route: "streetAddress",
            locality: "neighborhood",
            administrative_area_level_1: "state",
            administrative_area_level_2: "city",
            country: "country",
            postal_code: "zipCode",
        }

        this.placeSearch = null;
        this.autocomplete = null;
        this.currnetForm = null;
        this.form = form;
        this.initAutocomplete();
        this.addressSelected = false;
        this.address = null;
    }

    initAutocomplete() {

        const input = this.getInput();

        if (!input) return;

        input.onfocus = this.geolocate;
        input.onblur = (e) => { if (!input.value) this.clean(); }

        this.autocomplete = new google.maps.places.Autocomplete(input, { types: ["geocode"] });

        // Avoid paying for data that you don't need by restricting the set of
        // place fields that are returned to just the address components.
        this.autocomplete.setFields(["address_component"]);

        // When the user selects an address from the drop-down, populate the
        // address fields in the form.

        this.autocomplete.currentContext = this;
        this.autocomplete.addListener("place_changed", this.fillInAddress);

        google.maps.event.addDomListener(input, "keydown", function (e) {
            if (e.keyCode == 13 && $(".pac-container:visible").length) {
                e.preventDefault();
            }
        });

        google.maps.event.addDomListener(input, "keyup", function (e) {

            const input = this.getInput();

            if (this.addressSelected && this.address != input.value) {
                input.value = "";
                this.addressSelected = false;
                this.clean();
            }

        }.bind(this));
    }

    dataBind(address) {

        if (address.streetAddress) {
            let num = address.streetNumber ? address.streetNumber + " " : "";
            this.getElement("street").value = num + address.streetAddress;
        }

        if (address.country) {
            this.getElement("country").value = address.country;
        }

        if (address.city) {
            this.getElement("city").value = address.city;
        }

        if (address.state) {
            this.getElement("state").value = address.state;
        }

        if (address.zipCode) {
            this.getElement("zipCode").value = address.zipCode;
        }
    }

    getElement(ClientId) {
        return this.form.querySelector(`input[data-client-id="${ClientId}"]`);
    }

    getInput() {
        return this.form.querySelector("input[data-address-auto-fill]");
    }

    fillInAddress() {

        // Get the place details from the autocomplete object.
        const place = this.currentContext.autocomplete.getPlace();
        this.currentContext.clean();
        const address = {};

        if (!place.address_components)
            return;

        for (const component of place.address_components) {
            const addressType = component.types[0];

            if (this.currentContext.componentForm[addressType]) {
                const val = component[this.currentContext.componentForm[addressType]];
                const propertyName = this.currentContext.formMap[addressType]
                address[propertyName] = val;
            }
        }

        this.currentContext.dataBind(address);
        this.currentContext.address = this.currentContext.getInput().value;
        this.currentContext.addressSelected = true;
    }

    clean() {
        const inputs = this.form.querySelectorAll("input[data-client-id]");

        if (!inputs) return;

        for (const input of inputs)
            input.value = "";
    }

    isValid() {

        return (this.getElement("street").value &&
            this.getElement("country").value &&
            this.getElement("city").value &&
            this.getElement("state").value &&
            this.getElement("zipCode").value);
    }

    geolocate() {
        var pattern = /https/g;

        if (!pattern.test(location.protocol)) return;

        if (navigator.geolocation) {
            navigator.geolocation.getcurrentposition((position) => {
                const geolocation = {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude,
                };
                const circle = new google.maps.circle({
                    center: geolocation,
                    radius: position.coords.accuracy,
                });
                this.autocomplete.setbounds(circle.getbounds());
            });
        }
    }
}

function initAutocomplete() {

    const forms = document.querySelectorAll("form");

    if (!forms) return;

    for (const form of forms) {
        AddressAutoFill.create(form);
    }
}

;
//////////////////////////
// Patches
(function () {
    if (typeof NodeList.prototype.forEach === "function") return false;
    NodeList.prototype.forEach = Array.prototype.forEach;

    if (typeof Object.assign != "function") {
        // Must be writable: true, enumerable: false, configurable: true
        Object.defineProperty(Object, "assign", {
            value: function assign(target, varArgs) { // .length of function is 2
                "use strict";
                if (target == null) { // TypeError if undefined or null
                    throw new TypeError("Cannot convert undefined or null to object");
                }

                const to = Object(target);

                for (let index = 1; index < arguments.length; index++) {
                    const nextSource = arguments[index];

                    if (nextSource != null) { // Skip over if undefined or null
                        for (let nextKey in nextSource) {
                            // Avoid bugs when hasOwnProperty is shadowed
                            if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
                                to[nextKey] = nextSource[nextKey];
                            }
                        }
                    }
                }
                return to;
            },
            writable: true,
            configurable: true
        });
    }
})();

(function (arr) {
    arr.forEach(function (item) {
        if (item.hasOwnProperty("append")) {
            return;
        }
        Object.defineProperty(item, "append", {
            configurable: true,
            enumerable: true,
            writable: true,
            value: function append() {
                const argArr = Array.prototype.slice.call(arguments);
                var docFrag = document.createDocumentFragment();

                argArr.forEach(function (argItem) {
                    const isNode = argItem instanceof Node;
                    docFrag.appendChild(isNode ? argItem : document.createTextNode(String(argItem)));
                });

                this.appendChild(docFrag);
            }
        });
    });
})([Element.prototype, Document.prototype, DocumentFragment.prototype]);

if (window.Element && !Element.prototype.closest) {
    Element.prototype.closest =
        function (s) {
            const matches = (this.document || this.ownerDocument).querySelectorAll(s);
            var i,
                el = this;
            do {
                i = matches.length;
                while (--i >= 0 && matches.item(i) !== el) { };
            } while ((i < 0) && (el = el.parentElement));
            return el;
        };
}
// Patches
//////////////////////////;


/*-------lazy loading background images ----*/
document.addEventListener("DOMContentLoaded", function () {
    
    const offset = 900; //px before user srolls to the image.
    let lazyloadThrottleTimeout;
    

    function lazyload() {
        let lazyloadImages = document.querySelectorAll("[data-bgsrc]");
        if (lazyloadThrottleTimeout) {
            clearTimeout(lazyloadThrottleTimeout);
        }

        lazyloadThrottleTimeout = setTimeout(function () {
            let scrollTop = window.pageYOffset;
                
            lazyloadImages.forEach(function (img) {
                if (img.offsetTop < offset + (window.innerHeight + scrollTop)) {
                    img.style["backgroundImage"] = img.dataset.bgsrc;
                    img.removeAttribute('data-bgsrc');
                }
            });
            if (lazyloadImages.length == 0) {
                document.removeEventListener("scroll", lazyload);
                window.removeEventListener("resize", lazyload);
                window.removeEventListener("orientationChange", lazyload);
            }
        }, 1);
    }

    document.addEventListener("scroll", lazyload);
    window.addEventListener("resize", lazyload);
    window.addEventListener("orientationChange", lazyload);
    lazyload();
});

(function () {
    const formStuff = (function () {

        function focusMe($this) {
            $($this).parents(".form-group").addClass("form-group--focus");
        }

        function blurMe($this) {
            $($this).parents(".form-group").removeClass("form-group--focus");
        }

        return {
            focus: focusMe,
            blur: blurMe
        };
    })();

    //  1.0 Dropdown
    $(".selectric").selectric({

        disableOnMobile: false,
        nativeOnMobile: false,

        onOpen: function () {
            formStuff.focus($(this));
        },
        onClose: function () {
            formStuff.blur($(this));
        }
    })


    //  2.0 Input Focus
    $(".form-group__input").on("focus", function () {
        formStuff.focus($(this));
    });

    $(".form-group__input").on("blur", function () {
        formStuff.blur($(this));
    });

    function startLightGallery(videoSiblings, selectorLink) {

        if (!document.querySelector(videoSiblings)) return;

        $(videoSiblings).each(function (item) {
            let tagName = $(this).find(selectorLink).attr("name");
            if (tagName) tagName = tagName.replace("{", "").replace("}", "");

            /*added because light gallery needs a selector, href or data-src. 
             * if none exist, errors can happen.*/
            if (this.querySelector(selectorLink) == null &&
                this.querySelector("[href]") == null &&
                this.querySelector("[data-src]") == null)
                return;

            $(this).lightGallery({
                selector: selectorLink,
                width: "100%",
                youtubePlayerParams: {
                    autoplay: 1
                },
                galleryId: item + selectorLink.replace(".", "") + (tagName || ""),
                fullScreen: true
            });
        });
    }

    startLightGallery(".home-warranty__group", ".home-warranty__link");
    startLightGallery(".comments", ".comments__link");
    startLightGallery(".home-lifestyle__cards", ".home-card__link");
    startLightGallery(".card", ".vid-link");
    startLightGallery(".hero__carousel", ".hero-carousel__link");
    startLightGallery(".hero", ".hero-carousel__link"); // do not use on hero
    startLightGallery(".section__cards", ".home-card__link");
    startLightGallery(".showcase__small-inner", ".video-link");
    startLightGallery(".showcase__full", ".video-link");
    startLightGallery(".residence__gallery", ".video-link");
    startLightGallery(".early-move__media", ".video-link");
    startLightGallery(".comments__media", ".video-link");
    startLightGallery(".accordion-vid", ".video-page__link");
    startLightGallery(".vid-img", ".video-link");
    startLightGallery(".image-grid", ".video-link");
    startLightGallery(".btn-image-block--modal", ".btn-image-block--modal-link");

    $(".video-single").each(function () {
        var id = this.getAttribute("name");
        $(this).lightGallery({
            addClass: ".video-single",
            galleryId: id
        });
    });

    $(".image-single").each(function () {
        var id = this.getAttribute("name");
        $(this).lightGallery({
            addClass: "image-single",
            galleryId: id
        });
    });


    $(".early-move__card").each(function () {
        var id = this.getAttribute("name");
        $(this).lightGallery({
            addClass: "image-single",
            selector: ".early-move__link",
            galleryId: id
        });
    });

    //  3.0 Carousel

    function playOwlCarousel(selector, options, preloader) {

        const carousel = $(selector);

        const defaults = {
            lazyLoad: true,
            center: true,
            autoplay: true,
            loop: true,
            animateOut: false,
            video: false,
            autoplayTimeout: 6000,
            items: 1,
            nav: false,
            dots: true,
            margin: 0,
            responsiveClass: false
        };

        Object.assign(defaults, options);

        if (preloader == true) {
            carousel.on({
                'initialized.owl.carousel': function () {
                    carousel.find(".owl-item").show();
                    carousel.parents().children(".loading-placeholder").hide();
                }
            });
        };

        carousel.owlCarousel(defaults).trigger("refresh.owl.carousel");
    }

    $(".hero__carousel").each(function (index) {

        const autoplay = $(this).data("editing") != true;

        playOwlCarousel(this, {
            animateOut: "fadeOut",
            autoplay: autoplay
        }, true);
    });


    playOwlCarousel(".lifestyle__carousel", {
        nav: true,
        dots: false
    });

    playOwlCarousel(".comments__carousel");

    playOwlCarousel(".community__carousel", {
        autoplay: false,
        center: false,
        nav: true,
        dots: false,
        responsiveClass: true,
        responsive: {
            0: {
                items: 1
            },
            768: {
                items: 2,
                margin: 15
            },
            1024: {
                items: 3,
                margin: 30
            }
        }
    });

    playOwlCarousel(".showcase__carousel");

    playOwlCarousel(".carousel-block .carousel-images", {
        nav: true,
        dots: false
    });

    playOwlCarousel(".carousel-model",
        {
            items: 1,
            autoplay: true,
            loop: true,
            nav: true,
            dots: false
        });

    //  4.0 Gallery
    function createDragg() {

        if (document.querySelector(".lSPager-nav")) {

            const sliderWrapperHeight = document.querySelector(".lSSlideWrapper").offsetHeight;

            const navWrapper = document.querySelector(".lSPager-nav");
            const navInnerWrapper = navWrapper.querySelector(".lSPager-nav__inner");
            let dragCreated = false;
            let dragger;

            navWrapper.style.height = `${sliderWrapperHeight}px`;
            const lsPagerHeight = navWrapper.querySelector(".lSPager").offsetHeight;

            function computeChildWidth() {
                const children = Array.from(navInnerWrapper.children);
                return children.reduce((total, elem) => {
                    return total + elem.offsetHeight;
                }, 0);
            }

            function compareParentChild() {
                const childrenWidth = computeChildWidth();
                if (childrenWidth > navWrapper.offsetHeight && !dragCreated) {
                    navInnerWrapper.style.height = `${lsPagerHeight}px`;
                    createDraggable();
                } else if (childrenWidth < navWrapper.offsetHeight && dragCreated) {
                    removeDraggable();
                }
            }

            function createDraggable() {
                dragCreated = true;
                dragger = Draggable.create(navInnerWrapper, {
                    type: "y",
                    bounds: navWrapper,
                    throwProps: true,
                    dragClickables: true,
                    minimumMovement: 15
                });
            }

            compareParentChild();
        }
    }

    function responsiveSliderHeight() {
        const wrapperImageHeight = $(".gallery__data img").height();

        function setHeight() {
            $(".lslide").height(wrapperImageHeight);
        }

        $(window).on("resize", function () {
            setHeight();
        });

        setHeight();
    };

    // Feature Styling
    function kioskFeatureStyling() {
        const body = document.querySelector("body");

        if (window.location.href.indexOf("?sc_device=floorplan") > -1 || window.location.href.indexOf("?Sc_device=floorplan") > -1) {
            body.classList.add("is-kiosk");
        }
    }
    kioskFeatureStyling();





    //  5.0 Residence Drop
    $("#rdropResidence").on({
        'click': function () {
            $(this).parents(".r-drop").toggleClass("r-drop--show");
        },
        'focusout': function () {
            $(this).parents(".r-drop").removeClass("r-drop--show");
        }
    });

    // 7.0 Accordion
    function createAccordion(accordionCta, accordionItem, accordionPanel) {
        $(accordionCta).on("click", function (e) {
            e.preventDefault();

            const $this = $(this);
            const $thisParent = $this.parents(accordionItem);

            const $content = $thisParent.find(accordionPanel);

            if (!$thisParent.hasClass("is-closed")) {
                TweenLite.to($content, 0.2, {
                    height: 0
                });
                $thisParent.addClass("is-closed");
            } else {
                TweenLite.set($content, {
                    height: "auto"
                });
                TweenLite.from($content, 0.2, {
                    height: 0
                });
                $thisParent.removeClass("is-closed");
            }

            if (document.querySelector(".photoset-grid")) {
                $(".photoset-grid").photosetGrid({
                    gutter: "16px",
                    highresLinks: true,

                    onComplete: function () {
                        $(".photoset-grid").lightGallery({
                            selector: ".photoset-grid div a"
                        });
                    }
                });
            }
        });
    };

    createAccordion(".accordion__cta", ".accordion__item", ".accordion__panel");
    createAccordion(".tabs-accordion__cta", ".tabs-wrapper--accordion .tab__content", ".tabs-content__outer");

    $("#accordion").on("click", ".tabs-accordion-cta__symbol", function () {
        $(this).toggleClass("active").next().slideToggle();
        var plus = $(this).find('.icon__plus-thin');
        var minus = $(this).find('.icon icon__minus-thin');

        if (plus.css('opacity') == 1) {
            plus.css('opacity', '0');
            minus.css('opacity', '1');
        } else {
            plus.css('opacity', '1');
            minus.css('opacity', '0');
        }
    });

    $(".tabs-wrapper--accordion").find(".tab__content").not(":first-child").addClass("is-closed");
    $(".tabs-wrapper--accordion").find(".tab__content").not(":first-child").find(".tabs-content__outer").css("height", 0);

    if (document.querySelector("#collectionTabs")) {
        let collectionURL = window.location.href.replace(/\/$/, "");;
        let collectionName = collectionURL.substr(collectionURL.lastIndexOf("/") + 1);

        let collectionNameFormatted = collectionName.split("-")
            .join(" ")
            .toLowerCase()
            .split(" ")
            .map((s) => s.charAt(0).toUpperCase() + s.substring(1))
            .join(" ");

        let tabContents = document.querySelectorAll(".tab__content");
        tabContents.forEach(function (tabContent) {
            if ($(tabContent).find(".tabs-accordion-cta__heading").html().indexOf(collectionNameFormatted) > -1) {
                $(".tabs-wrapper--accordion").find(".tab__content").addClass("is-closed");
                $(".tabs-wrapper--accordion").find(".tab__content").find(".tabs-content__outer").css("height", 0);

                $(tabContent).removeClass("is-closed");
                $(tabContent).find(".tabs-content__outer").css("height", "auto");
            }
        });
    }

    // 8.0 Early Move In - View More
    function showViewMore() {
        $(".early-move__card").each(function () {
            const $this = $(this);
            const childrenAmount = $this.find(".early-move__items").children("li").length;

            if (childrenAmount > 3) {
                $this.find(".early-move__list").addClass("has-multiple-children");
            } else if (childrenAmount == 3) {
                $this.find(".early-move__list").addClass("has-three-children");
            }
        })
    }
    showViewMore();

    $(".early-move .btn").on("click", function (e) {
        e.preventDefault();
        const $this = $(this);

        $this.parent(".early-move__list").addClass("is-open");
    });

    // 9.0 Hero Down Indicator


    $(".hero__down-indicator").on("click", function (e) {
        e.preventDefault();

        const $this = $(this);
        const $thisParent = $this.parents(".hero");
        const $thisParentHeight = $thisParent.height();
        const $thisParentOffset = $thisParent.offset().top;
        const $secondaryNav = $(".wrapper--header").children(".secondary-wrapper");
        const $secondaryNavHeight = $secondaryNav.outerHeight();
        const $body = document.body;

        const $totalHeight = $thisParentHeight + $thisParentOffset + 1;

        TweenLite.to(window, 1, {
            scrollTo: $totalHeight
        })

        if ($secondaryNav.length) {
            const $totalHeight2 = $totalHeight - $secondaryNavHeight;

            TweenLite.to(window, 1, {
                scrollTo: $totalHeight2
            })
        }

        if ($body.classList.contains("fixed-arrow")) {
            $body.classList.remove("fixed-arrow");
        }
    });

    // 10.0 Detecting Secondary Nav
    if ($(".secondary-wrapper").length) {
        $("body").addClass("has-secondary-nav");
    }

    // 11.0 Call Button

    const showBox = function (trigger, content) {
        const _trigger = document.querySelector(trigger);
        const _content = document.querySelector(content);
        const _contentShow = `${content}--show`.replace(".", "");
        const _close = document.querySelector(`${content}__close`);

        _trigger.addEventListener("click", function (e) {
            e.preventDefault();
            _content.classList.add(_contentShow);
        });

        _close.addEventListener("click", function (e) {
            _content.classList.remove(_contentShow);
        })
    }

    if (document.querySelector(".call")) {
        let callShowBox = new showBox(".nav__call", ".call");
    }

    if (document.querySelector(".action--share")) {
        let shareShowBox = new showBox(".action--share", ".share");
    }

    // 12.0 Home Warranty - Vendor URL Redirect 
    $("#homeWarrantyCommunityList").on("change", function () {
        const url = $(this).val();
        if (url) {
            window.open(url);
        }
        return false;
    });

    // 13.0 Print after click on previous page
    const printURL = function () {
        if (window.location.href.indexOf("?print") > -1) {
            window.print();
        }
    };
    printURL();

    // 14.0 Moving Floorplan Residence Name on Desktop View
    const residenceNameMove = function () {
        const residenceName = document.querySelector(".residence__name");
        const residenceBody = document.querySelector(".residence__body");
        $(residenceName).prependTo(residenceBody);
    };
    residenceNameMove();

    const allTabs = [];
    const tabStart = function () {
        if (!document.querySelector(".tabs-wrapper")) return;

        const domTabs = document.querySelectorAll(".tabs-wrapper");
        if (!allTabs.length) {
            domTabs.forEach(tab => {
                allTabs.push(new Tabs(tab));
            });
        }

        allTabs.forEach(tab => {
            tab.isScrollNeeded();
        })
    }
    tabStart();

    $(window).on("resize", _.debounce(function () {
        createDragg();
        tabStart();
    }, 400));

    // 15.0 Nav Chat
    $(".nav__chat").hover(function () {
        $(this).siblings(".nav__chat-static").addClass("nav__chat-static--hover");
    }, function () {
        $(this).siblings(".nav__chat-static").removeClass("nav__chat-static--hover");
    });


    // it adds a scrollbar to communities dropdown menu to prevent menu items from being overlapped on some screen resolutions.
    (function () {

        function configMenuScrollBar() {
            const header = document.querySelector('header.wrapper--header div.header');
            const dropDownMenulist = document.querySelectorAll('header ul.nav li.nav__item .sub-nav')
           
            if (!header || !dropDownMenulist) return;

            const maxDropdownMenuHeight = (window.innerHeight - header.offsetHeight) - 5;

            for (const dropDown of dropDownMenulist) {
                const sections = dropDown.querySelectorAll(".sub-nav__section");

                for (const section of sections) {
                    section.style.overflowY = 'auto';
                    section.style.maxHeight = maxDropdownMenuHeight + 'px';
                }
            }
        
        }

     window.addEventListener("load", configMenuScrollBar);
     window.addEventListener("resize", configMenuScrollBar);
    })();

    // 16.0 Custom Print
    $(".btnPrint").printPage();

    // 17.0 Add Fixed Hero Down Indicator 
    function positionHeroContent() {

        if (!document.querySelector(".hero")) {
            // if hero does not exist.. then dont run this function at all..
            return;
        }

        function getMaxBottomValue(value) {

            const hero = document.querySelector('.hero');
            const headLine = hero.querySelector('.hero-headline');
            const heroInner = hero.querySelector('.hero__inner');

            if (!hero || !headLine || !heroInner)
                return value;

            const maxBottomValue = (hero.offsetHeight - (headLine.offsetHeight + heroInner.offsetHeight)) * 0.95;

            return Math.min(maxBottomValue, value);
        }

        function getViewportInfo() {
            const body = document.body;
            const main = body.querySelector(".wrapper--body");
            const hero = body.querySelector(".hero");
            const header = body.querySelector(".wrapper--header");
            const heroHeight = (hero) ? hero.offsetHeight : 0;
            const headerHeight = (header) ? header.offsetHeight : 0;
            const headerHeroHeight = headerHeight + heroHeight;
            const windowHeight = window.innerHeight;
            const heroInners = body.querySelectorAll(".hero__inner");
            const owlDots = body.querySelector(".owl-dots");
            const bottomDistance = headerHeroHeight - windowHeight;
            const scrollTop = window.pageYOffset;
            const mainOffsetTop = (main) ? main.offsetTop : 0;
            const heroInnerBottomDistance = (bottomDistance + 80) - scrollTop;
            const dotsBottomDistance = (bottomDistance + 15) - scrollTop;

            return {
                isHeroOverflow: headerHeroHeight > windowHeight,
                body,
                main,
                headerHeroHeight,
                windowHeight,
                heroInners,
                owlDots,
                scrollTop,
                mainOffsetTop,
                heroInnerBottomDistance,
                dotsBottomDistance,
            };
        }
        let infoFixArrow = getViewportInfo();

        function addFixedArrow() {
            infoFixArrow.body.classList.add("fixed-arrow");
            if (infoFixArrow.heroInners)
                infoFixArrow.heroInners.forEach(heroInner => heroInner.style.bottom = getMaxBottomValue(infoFixArrow.heroInnerBottomDistance) + "px");
            if (infoFixArrow.owlDots)
                infoFixArrow.owlDots.style.bottom = infoFixArrow.dotsBottomDistance + "px";
        }

        function removeFixedArrow() {
            infoFixArrow.body.classList.remove("fixed-arrow");
            if (infoFixArrow.heroInners)
                infoFixArrow.heroInners.forEach(heroInner => heroInner.removeAttribute("style"));
            if (infoFixArrow.owlDots)
                infoFixArrow.owlDots.removeAttribute("style");
        }

        function addOverflow() {
            infoFixArrow.body.classList.add("is-overflow");
        }

        function removeOverflow() {
            infoFixArrow.body.classList.remove("is-overflow");
        }

        function checkFixedArrow() {

            infoFixArrow = getViewportInfo();

            if (document.querySelector(".is-overflow") && infoFixArrow.isHeroOverflow && infoFixArrow.heroInnerBottomDistance > 0 && infoFixArrow.dotsBottomDistance > 0) {
                addFixedArrow();
            } else if (document.querySelector(".is-overflow") && infoFixArrow.isHeroOverflow && infoFixArrow.heroInnerBottomDistance < 0 && infoFixArrow.dotsBottomDistance < 0) {
                removeFixedArrow();
            }
        }

        if (infoFixArrow.isHeroOverflow && infoFixArrow.heroInnerBottomDistance > 0 || infoFixArrow.dotsBottomDistance > 0) {
            addFixedArrow();
            addOverflow();
        } else {
            removeFixedArrow();
            removeOverflow();
        }

        window.addEventListener("scroll", checkFixedArrow);
    }

    if (document.querySelector(".hero")) {
        positionHeroContent();
        $(window).on("resize", function () {
            setTimeout(positionHeroContent, 1000);
        });
    }

    // 18.0 Article Spacing 
    function hideArticleHTMLSpacing() {
        const articleText = document.querySelector(".article-layout__text");
        const regEx = /&nbsp;/gm;
        const articleParagraphs = articleText.querySelectorAll("p");
        const elements = $(".article-layout__text p").filter(function (index, ele) {
            if (regEx.test($(ele).html())) {
                return true;
            }
        });
        articleParagraphs.forEach(articleParagraph => articleParagraph.innerHTML = articleParagraph.innerHTML.replace(/&nbsp;/, ""));
    }
    if (document.querySelector(".article-layout__text")) {
        hideArticleHTMLSpacing();
    }

    function hoverNav() {
        $(".nav__item:has('.sub-nav')").addClass("has-children");

        $(".nav__item.has-children").hover(function () {
            $(this).addClass("hover");
        }, function () {
            $(this).removeClass("hover");
        });
    };
    hoverNav();

    // FORM SUBMISSION TRACKING
    /////////////////////////////////////

    if ($$epiforms) {
        $$epiforms(".EPiServerForms").on("formsSubmitted", function (event, param1, param2) {
            // make sure form succeeded and the data layer is already initialized
            if (!dataLayer || !event.isFinalizedSubmission || !event.isSuccess) return;

            // interrogate the fields to see if there is any community fields
            const form = $$epiforms(this);

            // grab the communities we collected while submitting
            const communities = form.data("selectedCommunities") || "";

            const data = {
                "event": "formSubmission",
                "formType": event.workingFormInfo.Name,
                "pageUrl": window.location.pathname,
                "communities": communities
            };
            dataLayer.push(data);
            console.log(JSON.stringify(data));
        });

        $$epiforms(".EPiServerForms").on("formsStartSubmitting", function (event, param1, param2) {
            if (!dataLayer) return;

            const form = $$epiforms(this);
            const communities = [];
            for (const [key, value] of Object.entries(event.workingFormInfo.ElementsInfo)) {
                if (!value) continue;
                if (value.type.toLowerCase().indexOf("community") > -1 ||
                    value.friendlyName.toLowerCase().indexOf("community") > -1 ||
                    value.friendlyName.toLowerCase().indexOf("communities") > -1) {

                    const field = form.find(`:input[name=${key}]`);

                    if (field && field.length) {
                        if (field.is("select")) {
                            for (const item of field[0]) {
                                if (item.selected) {
                                    const community = parseCommunity(item.value);
                                    if (community && !communities.includes(community))
                                        communities.push(community);
                                }
                            }
                        }
                        else {
                            if (field.is(":checkbox")) {
                                for (const item of field) {
                                    if (item.checked) {
                                        const community = parseCommunity(item.value);
                                        if (community && !communities.includes(community))
                                            communities.push(community);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // store the collected communities on the form for when submission completes
            form.data("selectedCommunities", communities.join(", "));

            function parseCommunity(value) {
                if (!value) return value;
                const pattern = /(.+)\w?\([\d\,\w]+\)/i;
                const match = pattern.exec(value);
                if (!match) return value;
                return match[1].trim();
            }
        });
    }
})();


if (document.querySelector(".wrapper--floorplans")) {
    const fpz = new FloorPlanZoomer(".wrapper--floorplans");
}
if (document.querySelector(".wrapper--highlights") && highlightData.length > 0) {
    const fphl = new FloorplanHighlights(".wrapper--highlights");
}

if (document.querySelector(".find-home__map")) {
    var currentUrl = window.location.href;
    var styleGuidePageName = "style-guide";
    if (currentUrl.indexOf(styleGuidePageName) !== -1) {
        const locData = [{
            "LocationId": "bea26091-70e2-4789-9aa3-76e4978f8509",
            "LocationName": "boca-raton",
            "Coordinates": "444,468",
            "Communities": [{
                "CommunityId": "b3ef72c0-c3ee-44f1-87eb-72c9974e34b6",
                "LocationName": "boca-raton",
                "RegionName": "East Coast"
            }, {
                "CommunityId": "d06e9a01-5180-42d7-befe-ad9e062f8581",
                "LocationName": "boca-raton",
                "RegionName": "East Coast"
            }]
        }, {
            "LocationId": "d1c36193-38d8-4738-acf3-d76971c08e9f",
            "LocationName": "delray-beach",
            "Coordinates": "445,445",
            "Communities": [{
                "CommunityId": "258aace7-6698-4c98-aee5-f6e4ff15116f",
                "LocationName": "delray-beach",
                "RegionName": "East Coast"
            }]
        }, {
            "LocationId": "f12ed7c1-cf2b-404b-819d-030d28307fae",
            "LocationName": "fort-myers",
            "Coordinates": "215,477",
            "Communities": [{
                "CommunityId": "958f5ec4-79d0-44c7-b416-e34442925577",
                "LocationName": "fort-myers",
                "RegionName": "West Coast"
            }]
        }, {
            "LocationId": "09d8c9d8-0220-4557-9ae3-5d4ee7f4e029",
            "LocationName": "tampa",
            "Coordinates": "182,391",
            "Communities": [{
                "CommunityId": "5cc35ad6-d623-4c38-a010-aa9dc0b23a2a",
                "LocationName": "tampa",
                "RegionName": "West Coast"
            }]
        }];

        const displayCities = new PlaceCity(".find-home__map", locData);
    } else {
        const locData = communityLocationData;
        const displayCities = new PlaceCity(".find-home__map", locData);
    }
}

// Structural Options

if (document.querySelector(".structural-wrapper")) {
    const structOpt = new StructuralOptions(".structural-wrapper");
}

if (document.querySelector(".flyout__section[data-location]")) {
    const sMap = new StaticMap(".flyout__section[data-location]");
}

if (document.querySelector(".community-directions div[data-location]")) {
    const cMap = new StaticMap(".community-directions div[data-location]");
}

var gaSubmit = (function () {
    const event = function (category, action, label) {
        var tracker;
        if ("ga" in window && ga.loaded) {
            tracker = ga.getAll()[0];
        }
        if (tracker !== undefined) {
            //console.log('tracker Send ' + category +' '+ action +' '+ label);
            tracker.send("event", category, action, label);
        } else {
            console.log("No GA");
        }
    };

    return {
        event: event
    };
})();


(function () {
    $('.start-chat').on('click', function (e) {
        e.preventDefault();
        $(".bcStatic > a").trigger("click");
    });
})();

(function () {
    let boldChat = document.getElementsByClassName('nav__chat')[0];

    let sleep = time => new Promise(resolve => setTimeout(resolve, time))
    let poll = (promiseFn, time) => promiseFn().then(
        sleep(time).then(() => poll(promiseFn, time)))

    if (boldChat) {
        poll(() => new Promise(() => {
            let isBoldChatOpen = window.bcChatWindows && window.bcChatWindows.length > 0;

            if (isBoldChatOpen) {
                boldChat.classList.add('hide-bold-chat');
            }
            else {
                boldChat.classList.remove('hide-bold-chat');
            }

        }), 1000)
    }
})();


$(document).ready(function () {

    /*
    By default, embedded youtube videos are not responsive.
    This function allow them behave responsive on article pages.
    It also sets related videos to show only videos related to GL Home, once it is not possible disable them any more.
    */
    (function () {

        var frames = $(".article-layout__body iframe[src^='https://www.youtube.com']") || [];

        if ("length" in frames) {
            $(frames).each(function (index, el) {
                $(el).removeAttr("width");
                $(el).removeAttr("height");
                $(el).wrap('<div class="video-container"></div>');
                var pattern = /\?/g;
                var url = $(el).attr("src");
                url = pattern.test(url) ? url.concat("&rel=0") : url.concat("?rel=0");
                $(el).attr("src", url);
            });
        }
    })();

    /*
      This function replace image url from http to https when the site is using https protocol. Only for articles pages.
     */
    (function () {

        var pattern = /https/g;

        if (!pattern.test(location.protocol))
            return;

        var links = $(".article-layout__body img[src^='http:']") || [];

        if ("length" in links) {

            $(links).each(function (index, el) {
                var src = $(el).attr("src");
                src = src.replace(/http:/, "https:")
                $(el).attr("src", src);

                var srcset = $(el).attr("srcset");

                if (srcset) {
                    srcset = srcset.replace(/http:/g, "https:")
                    $(el).attr("srcset", srcset);
                }
            })
        }
    })();

    $('.modal-backdrop.interactive-image-popup').click(function (e) {
        if ($(e.target).hasClass('modal-backdrop')) {
            $(e.target).removeClass("shown")
        } else if ($(e.target).hasClass('popup-inner')) {
            $(e.target.parentElement).removeClass("shown");
        }
    });
    
    
    
});

(function () {
    /**
     Chat Banner block:
     It sets the block height taking into consideration its image size
     **/
    function setChatBannerBlockHeight() {
        const blocks = document.querySelectorAll('section.chat-banner-block');

        if (!("length" in blocks && blocks.length))
            return;

        for (var i = 0; i < blocks.length; i++) {
            const section = blocks[i];
            const image = section.querySelector('.image-chat > img');
            const content = section.querySelector('.chat-banner-block__content');

            if (!image)
                return;

            const height = getHeight(content.offsetHeight, image.height);
            section.setAttribute("style", `padding-top: ${height}px; transition: padding-top 0.25s ease;`);
        }
    }

    function getHeight(bannerHeight, imageHeight) {
        let result = 0;
        const isMobile = isMobileScreen();

        if (isMobile) {
            result = imageHeight;
        } else {

            if (bannerHeight > imageHeight) {
                result = bannerHeight - imageHeight;

            } else {
                result = imageHeight - bannerHeight;
            }
        }

        return result;
    }

    function isMobileScreen() {
        return window.innerWidth <= 1024;
    }

    window.addEventListener('load', setChatBannerBlockHeight);
    window.addEventListener('resize', setChatBannerBlockHeight);
    window.addEventListener("orientationchange", setChatBannerBlockHeight);
})();


(function () {

    function setPromoBannerHeight() {
        const sections = document.querySelectorAll(".promo-banner-with-image-section");
        
        for (const section of sections) {
            if (section && window.innerWidth >= 768) {
                const imageHeight = section.querySelector(".image-left").clientHeight;
                const blockHeight = section.clientHeight;

                if (imageHeight > blockHeight) {
                    const height = imageHeight - blockHeight + 20;
                    section.setAttribute("style", `padding-top: ${height}px; transition: padding-top 0.25s ease;`);
                }
            } else {
                section.setAttribute("style", `padding-top: 0px; transition: padding-top 0.25s ease;`);
            }
        }
    }

    window.addEventListener("load", setPromoBannerHeight);
    window.addEventListener("resize", setPromoBannerHeight);
    window.addEventListener("orientationchange", setPromoBannerHeight);
})();

/** Button Image Block **/
$(document).ready(() => {

    const buttons = document.querySelectorAll(".btn-image-block");

    for (const btn of buttons) {

        btn.addEventListener("click", (e) => {
            e.preventDefault();
            const { id } = btn;
            const fakeImage = document.querySelector(`span[data-image-id="${id}"]`);
            fakeImage.click();
        });
    }

});


/*-------Fixed Footer Bar--------*/
(
    function () {
        $(window).on("load", function () {
            var footerBar = document.querySelector(".fixed-footer-bar");
            if (footerBar == null)
                return;

            var extraSpace = document.createElement("div");
            document.body.appendChild(extraSpace);

            resizeExtraSpaceHeight();

            function resizeExtraSpaceHeight() {
                if (footerBar == null || !$.isNumeric(footerBar.offsetHeight))
                    return;
                extraSpace.style.height = footerBar.offsetHeight + "px";
            }

            var timeout;
            $(window).on("resize", function () {
                clearTimeout(timeout);
                timeout = setTimeout(resizeExtraSpaceHeight, 500);
            });

        });
    }
)();


/*-------Scroll nav on mobile--------*/
(function () {
var isMobile;
const nav = document.querySelector('ul.nav');
$(".nav__item.has-children").on("click", function () {
    var subNavOpen = nav.classList.contains("scroll");
    if (subNavOpen)
        $(nav).removeClass('scroll');
    else {
        if (isMobile) {
            $(nav).addClass('scroll');
        }
    }
});

// Create a condition that targets viewports less than, or equal to, 768 pixels wide
const mediaQuery = window.matchMedia('(max-width: 768px)');

function handleMobileChange(e) {
    // Check if the media query is true
    if (e.matches)  isMobile = true;
    else {
        isMobile = false;
        $(nav).removeClass('scroll');
    }
}
// Register event listener
mediaQuery.addListener(handleMobileChange);
// Initial check
handleMobileChange(mediaQuery);
})();
;
$(function () {
    $('.filter-choice').click(function () {
        $('.filter-view').toggle();
        $('.tabs-link-wrapper').toggle();
        $('.list-view').toggle();
    });
});;
