$(function () {
    var locationURL = window.location.pathname.split('/');
    var directoryURL = locationURL[1];

    $('#navbarNavDropdown > ul > li > a').each(function () {
        var item = $(this);
        var href = item.attr('href').split('/')[1];
        href.toLowerCase() == directoryURL.toLowerCase() ? item.addClass('active') : item.removeClass('active');
    });

    /* Vimeo player */
    var $videoSrc;
    $('.vimeo').click(function () {
        $videoSrc = $(this).find(".vimeo-url").data("src");
    });
    $('#videoModal').on('shown.bs.modal', function (e) {
        $("#video").attr('src', $videoSrc + "?autoplay=1");
    });
    $('#videoModal').on('hide.bs.modal', function (e) {
        $("#video").attr('src', $videoSrc);
    });

    var box = $('#top-search-container .search-form-wrapper');
    if ($('.Home').length === 0) {
        box.addClass('open');
        $('.search-open').addClass('d-none');
    } else {
        $('.search-label, .search-open').on('click',
            function (i, el) {
                box.hasClass('open') ? box.removeClass('open') : box.addClass('open');
                $('.search-open').hasClass('d-none')
                    ? $('.search-open').removeClass('d-none')
                    : $('.search-open').addClass('d-none');
            });
    }

    // Please don't delete the below comment out code. Might need to uncomment and use again in the future.  
    //var tempLink = $('nav.Home#top-nav .d-none.d-md-flex.float-left .tempLink');
    //if ($('.Home').length !== 0) {
    //    tempLink.html('<a target="_blank" href="https://projects.tulaliptribes-nsn.gov/Construction-Cameras/">Construction Cameras</a>');
    //}

    $('.cookie').off('click').on('click', function (prop1) {
        if (prop1.ctrlKey && prop1.shiftKey && prop1.altKey) {
            Cookies.set("Admin-Enabled", true, { expires: 0.04, path: "/" });
            location.reload();
        }
    });

    var url = $(location).attr('href').split("/").splice(0, 5).join("/");
    var hostname = extractHostname(window.location.href);
    var siteList = [
        'www.tulalipresortcasino.com',
        'www.quilcedacreekcasino.com',
        'www.quilcedavillage.com',
        'www.tulaliptv.com',
        'projects.tulaliptribes-nsn.gov',
        'userrightsmanagement.tulalipdata.com',
        'menu.tulalipmarket.com',
        'www.hibulbculturalcenter.org',
        'gis.tulaliptribes-nsn.gov',
        'tttlushootseed.tulalipdata.com',
        'nr.tulaliptribes.com',
        'www.quilcedavillage.com',
        'www.salishnetworks.com',
        'www.qwuloolt.org',
        'www.salishnetworks.com',
        'www.tulalipbingo.com',
        'www.tulalipbroadband.com',
        'www.tulalipcares.org',
        'www.tulalipclinicalpharmacy.com',
        'www.tulalipdata.com',
        'www.tulaliplushootseed.com',
        'www.tulalipmarket.com',
        'www.tulaliptero.com',
        'www.tulaliptribaljourney.org',
        'www.tulaliptribalpolice.org',
        'projects.tulaliptribes-nsn.gov',
        'share.tulaliptribes-nsn.gov',
        'employment.tulaliptribes-nsn.gov',
        'www.codepublishing.com',
        'www.tulalipnews.com',
        'www.quilcedavillage.org',
        'www.tulaliphealthsystem.com',
        'app.acuityscheduling.com',
        'online.fliphtml5.com',
        'www.tulalipfoundation.org'
    ];
    //var site_msg = ['You are about to leave the Tulalip Tribes Government Website.'];
    $("a").filter(function () {
        return this.hostname && this.hostname !== location.hostname;
    })
    .click(function () {
        if (extractHostname($(this).attr("href")) !== hostname) {
            const msg = 'You are about to leave the Tulalip Tribes Government Website and visit a third-party website that the Tulalip Tribes does not maintain or control. Privacy policies may vary from those of the Tulalip Tribes Government Website.';
            for (let i = 0; i < siteList.length; i++) {

                if (siteList[i] === extractHostname($(this).attr("href")))
                    $("a").live("click", function (e) {
                        window.open(this.href);
                        e.preventDefault(); //or return false;
                    });
            }
            if (confirm(msg)) {
                return true;
            } else
                return false;
        } else
            return true;
    });

    function extractHostname(url) {
        var hostname;
        //find & remove protocol (http, ftp, etc.) and get hostname

        if (url.indexOf("://") > -1) {
            hostname = url.split('/')[2];
        }
        else {
            hostname = url.split('/')[0];
        }

        //find & remove port number
        hostname = hostname.split(':')[0];
        //find & remove "?"
        hostname = hostname.split('?')[0];

        return hostname;
    }

    /* selected item for side nav */
    if ($('.left-page-nav')) {
        const h1 = $('h1'),
            links = $('.left-page-nav a');
        links.each(function (i, el) {
            let h1text = h1.text(),
                eltext = $(el).text();
            if (h1text.match(eltext)) {
                $(el).addClass('active')
            }
        });
    };

    // press releases
    $('.press-releases .label').on('click', function (e) {
        var parent = $(e.currentTarget).closest('.press-releases')
        parent.hasClass('open') ? parent.removeClass('open') : parent.addClass('open')
    });

    //forms
    hideLoadingGif();

    $('input[type="text"], textarea').on('blur', function () {
        this.value = $.trim(this.value);
    });

    /*Third Tier Nav */
    var thirdTierNavExists = $(".multiViewNavBg").length > 0;
    if (thirdTierNavExists) {
        $("section.webPageSection").each(function(e) {
            $(this).addClass("thirdTierNavSection");
        });
    }

    $(".multiViewItem").on("click", function(e) {
        $(".multiViewItem").removeClass("selectedMultiViewItem");
        $(this).addClass("selectedMultiViewItem");
        $("section.thirdTierNavSection .left-column-section").css("display", "none");
        var selectedViewId = $(this).attr("id");
        history.replaceState(window.location.href, "", window.location.href.substring(0, window.location.href.indexOf("?selectedView=")) + "?selectedView=" + selectedViewId);

        $("section.thirdTierNavSection .left-column-section").each(function() {
            var selectedView = $(this).find("." + selectedViewId);
            if (selectedView.length > 0) {
                $(this).css("display", "initial");
            }
        });

        //show right column, if unique to view
        var selectedRightColumn = $(".TDSRightColumn." + selectedViewId);
        if (selectedRightColumn.length > 0) {
            $(".TDSRightColumn").css("display", "none");
            $(".TDSRightColumn." + selectedViewId).css("display", "block");
        }
        else {
            $(".TDSRightColumn").css("display", "none");
            $(".TDSRightColumnDefault").css("display", "block");
        }

        //show contact form, if it exists for view
        var hasContactFormDiv = $(".hasContactForm." + selectedViewId)[0];
        var hasContactForm = typeof hasContactFormDiv !== "undefined" ? (hasContactFormDiv.innerText === "True" ? true : false) : false;

        if (hasContactForm) {
            $($(".row.ContactUs").parent()).css("display", "initial");
            var contactFormName = $(".hasContactForm." + selectedViewId).attr("data-name");

            $("select#Recipient option").each(function() {
                var dataName = $(this).attr("data-name");
                $(this).attr("hidden", dataName.indexOf(contactFormName) < 0);
                $(this).removeAttr("selected");
            });
            
            $($("select#Recipient option:not([hidden='hidden'])")[0]).attr("selected", true);

            if (selectedViewId === "ContactUs") {
                $("#contactFormHeader").css("display", "initial");
                $("#contactFormHr").css("display", "initial");
                $($("select#Recipient option")[0]).attr("selected", true);
            }
            else {
                $("#contactFormHeader").css("display", "none");
                $("#contactFormHr").css("display", "none");
            }
        }
    });

    // show popup image (Comprehensive plan page)
    $("div.imagePopup").on("click", function(e) {
        var modal = $(this).find(".popupModal");
        $(modal).css("display", "initial");
        $("div.sticky-top").css("position", "initial");
        $("div.sticky-top div.z-index-3").css("position", "initial");
    });

    //popup modal controls
    window.onclick = function(event) {
        if ($(event.target).hasClass("popupModal")) {
            event.target.style.display = "none";
            $("div.sticky-top").css("position", "sticky");
            $("div.sticky-top div.z-index-3").css("position", "relative");
        }
    }

    //change tab
    $(".changeTab").on("mousedown", function(e) {
        var selectedTab = $(this).attr("data-selectedtab");
        $(".multiViewItem#" + selectedTab).click();
    });

    //navigate to correct tab on page load
    if (window.location.href.indexOf("?selectedView=") > -1) {
        var selectedView = window.location.href.substring(window.location.href.indexOf("?selectedView=")).split("=")[1];
        $(".multiViewItem#" + selectedView).click();
    }
});

/* 
 * Overlay and validation controls for forms
 */
$('#PrivacyPolicyYes').on('click, touchstart', function () {
    var button = $(this).find('input[type="submit"]');
    button.removeClass('disabled');
});

$(document).on('invalid-form.validate', 'form', function () {
    if ($('#PrivacyPolicyYes').prop('checked')) {
        var button = $(this).find('input[type="submit"]');
        button.removeClass('disabled');
    }
});

$(document).on('submit', 'form', function () {
    var button = $(this).find('input[type="submit"]');
    button.addClass('disabled');
    $('.loading-gif').each(function () {
        showLoadingGif();
    });
});

var clear_form_elements = function (class_name) {
    jQuery("." + class_name).find(':input').each(function () {
        switch (this.type) {
            case 'password':
            case 'text':
            case 'textarea':
            case 'file':
            case 'select-one':
            case 'select-multiple':
            case 'date':
            case 'number':
            case 'tel':
            case 'email':
                jQuery(this).val('');
                break;
            case 'checkbox':
            case 'radio':
                this.checked = false;
                break;
        }
    });
};

function showLoadingGif() {
    if (grecaptcha.getResponse().length < 1) {
        $("#captchaError").css("display", "block");
        return false;
    }
    else {
        $("#captchaError").css("display", "none");
        $("input.contact.submit.ctrButton").removeClass("disabled");
        $([document.documentElement, document.body]).animate({
            scrollTop: $(".contactform").offset().top
        }, 100);
        $('.loading-gif').show();
        $('.loading-circle').show();
        $('.loading-whale').show();
    }
}

function hideLoadingGif() {
    $('.loading-circle').hide();
    $('.loading-gif').hide();
    $('.loading-whale').hide();
}

