function CalendarCardPaging(widgetId) {
    var take = $('#paging-take-' + widgetId);
    var skip = $('#paging-skip-' + widgetId);
    var guidList = $('#paging-guid-list-' + widgetId);
    var showDescriptions = $('#paging-show-descriptions-' + widgetId);
    var view = $('#paging-view-' + widgetId);
    var totalCount = $('#totalRecordCountSpan-' + widgetId);
    var resultsContainer = $('#cal-card-listing-' + widgetId);

    $.ajax({
        url: "/geteventresults",
        data: {
            viewName: view.val(),
            eventGuidStr: guidList.val(),
            skip: parseInt(skip.val()),
            itemsPerPage: parseInt(take.val()),
            showDescriptions: showDescriptions.val()
        },
        contentType: 'application/x-www-form-urlencoded',
        method: "POST",
        success: function (result) {
            //Append new results. Update counters.
            resultsContainer.append(result);

            var skipInt = parseInt(skip.val());
            var takeInt = parseInt(take.val());
            var totalCountInt = parseInt(totalCount.text());
            skipInt = skipInt + 1;
            skip.val(skipInt);

            //We are at the end of the results. Hide load more.
            if (skipInt * takeInt >= totalCountInt) {
                $("#loadedCardContent-" + widgetId + " #loadMoreCalendarCardResults-" + widgetId).hide();
                $("#currentDisplayCountSpan-" + widgetId).html(totalCountInt);
            } else {
                $("#currentDisplayCountSpan-" + widgetId).html(skipInt * takeInt);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("Status: " + textStatus); alert("Error: " + errorThrown);
        }
    });
}
function cardWidgetPaging(widgetIdentifier) {

    var pagingGuidsInput = $("#" + widgetIdentifier + "_pagingGuidsInputTest").val();
    var currentDisplayCount = $("#" + widgetIdentifier + "_currentDisplayCountSpan").html();
    var totalRecordCountInput = $("#" + widgetIdentifier + "_totalRecordCountInputTest").val();
    var cardWidgetPropertiesTests = $("#" + widgetIdentifier + "_cardWidgetPropertiesTest").val();
    var resultsContainer = $("#" + widgetIdentifier + "_card-group__list");
    var apiUrl = '/cardpaging';

    $.ajax({
        url: apiUrl,
        data: {
            pagingGuidsTest: pagingGuidsInput,
            currentDisplayCount: currentDisplayCount,
            totalRecordCount: totalRecordCountInput,
            cardWidgetProperties: cardWidgetPropertiesTests
        },
        contentType: 'application/x-www-form-urlencoded',
        method: "POST",
        success: function (result) {
            //Append new results. Update counters.
            resultsContainer.append(result.View);

            $("#" + widgetIdentifier + "_currentDisplayCountSpan").html(result.NewCount);
            currentDisplayCount = result.NewCount;

            //We are at the end of the results. Hide load more.
            if (result.NewCount == result.TotalRecordCount) {
                 $("#" + widgetIdentifier + "_loadMoreResultCards").hide();
            }

        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("Status: " + textStatus); alert("Error: " + errorThrown);
        }
    });
}
$(function () {
    $('.js-eventSearch').each(function () {
        var $this = $(this);
        var widgetId = $this.attr('data-id');
        // read query string and set form values
        var startDate = getParameterByName('startdate');
        if (startDate) {
            $('#eventSearch-startDate-' + widgetId).val(startDate);
        }
        var endDate = getParameterByName('enddate');
        if (endDate) {
            $('#eventSearch-endDate-' + widgetId).val(endDate);
        }
        var keywords = getParameterByName('keywords');
        if (keywords) {
            $('#eventSearch-keywordText-' + widgetId).val(keywords);
        }
        var types = getParameterByName('types');
        if (types) {
            typeItems = types.split(',');
            if (typeItems.length > 0) {
                $('#eventSearch-typeList-' + widgetId).val(typeItems[0].replace("&", "&amp;"));
            }
        }
        var cities = getParameterByName('cities');
        if (cities) {
            cityItems = cities.split(',');
            if (cityItems.length > 0) {
                $('#eventSearch-cityList-' + widgetId).val(cityItems[0]);
            }
        }
    });

    // process form when search is clicked
    $('.js-eventSearch-submit').click(function (e) {
        e.preventDefault();
        var $this = $(this);
        var widgetId = $this.attr('data-id');
        processForm(widgetId);
    });

    // process form when enter key is pressed when keyword textbox in focus
    $('.js-eventSearch-keyword').keypress(function (e) {
        var key = e.which;
        if (key == 13)  // the enter key code
        {
            var $this = $(this);
            var widgetId = $this.attr('data-id');
            processForm(widgetId);
        }
    });
});

function processForm(widgetId) {
    var url = "";
    var queryStringItems = new Array();
    var eventSearchResultsPage = $('#eventSearch-searchButton-' + widgetId).attr('href');
    var startDate = $('#eventSearch-startDate-' + widgetId).val();
    var endDate = $('#eventSearch-endDate-' + widgetId).val();
    var keyword = $('#eventSearch-keywordText-' + widgetId).val();
    var typeSelected = $('#eventSearch-typeList-' + widgetId).find(":selected").val();
    var citySelected = $('#eventSearch-cityList-' + widgetId).find(":selected").val();

    url = url + eventSearchResultsPage;
    if (startDate.length > 0) {
        queryStringItems.push("startdate=" + startDate);
    }
    if (endDate.length > 0) {
        queryStringItems.push("enddate=" + endDate);
    }
    if (keyword.length > 0) {
        queryStringItems.push("keywords=" + keyword);
    }
    if (typeSelected.length > 0) {
        // have to encode ampersands to %26 within the value or JS to get query string values will break
        queryStringItems.push("types=" + typeSelected.replace("&amp;", "%26"));
    }
    if (citySelected.length > 0) {
        queryStringItems.push("cities=" + citySelected);
    }
    if (queryStringItems.length > 0) {
        url = url + "?" + queryStringItems.join("&");
    }
    window.location.href = url;
}

function clearEventSearchFormElements(widgetId) {
    $("#eventSearch-" + widgetId).find(':input').each(function () {
        $(this).val('');
    });
}

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
$(function () {
    // hide/show proper dropdown on page load (handles back button event)
    $('.js-itinerary-type-radio').each(function () {
        var $this = $(this);
        var id = $this.attr('data-id');
        var activityRadio = $('#activity-' + id);
        var locationRadio = $('#location-' + id);

        if (activityRadio && activityRadio.length > 0 && activityRadio[0].checked) {
            $("#locationList-" + id).parent('.js-itinerary-search__item').hide();
            $("#activityList-" + id).parent('.js-itinerary-search__item').show();
        } else if (locationRadio && locationRadio.length > 0 && locationRadio[0].checked) {
            $("#locationList-" + id).parent('.js-itinerary-search__item').show();
            $("#activityList-" + id).parent('.js-itinerary-search__item').hide();
        }
    });
});
window.onload = function () {
    const params = new Proxy(new URLSearchParams(window.location.search), {
        get: (searchParams, prop) => searchParams.get(prop),
    });
    if (params.activities != null) {
        $('input[value=activity]').prop("checked", true);
        $('input[value=location]').prop("checked", false);
        var selectedValue = params.activities.replace(/%20/g, " ");
        selectedValue = selectedValue.replace(/(?:^|\s)\S/g, function (a) { return a.toUpperCase(); });
        selectedValue = selectedValue.replace(/(?:^|[\s-/])\w/g, function (a) { return a.toUpperCase(); });
        if (selectedValue.includes("And")) {
            selectedValue = selectedValue.replace("And", "and");
        }
        if (selectedValue.includes("Non-Ski")) {
            selectedValue = selectedValue.replace("Non-Ski", "Non-ski");
        }
        $('.activities-list').val(selectedValue);
        $(".locations-list").parent('.js-itinerary-search__item').hide();
        $(".activities-list").parent('.js-itinerary-search__item').show();
    }
    else if (params.locations != null) {
        $('input[value=activity]').prop("checked", false);
        $('input[value=location]').prop("checked", true);
        var selectedValue = params.locations.replace(/%20/g, " ");
        selectedValue = selectedValue.replace(/(?:^|\s)\S/g, function (a) { return a.toUpperCase(); });
        selectedValue = selectedValue.replace(/(^|[\s-])\S/g, function (a) { return a.toUpperCase(); });
        $('.locations-list').val(selectedValue);
        $(".locations-list").parent('.js-itinerary-search__item').show();
        $(".activities-list").parent('.js-itinerary-search__item').hide();
    }

}

if (document.readyState === "loading") {
    // Calls the function during the 'DOMContentLoaded' event, after the HTML document has been completely loaded
    document.addEventListener("DOMContentLoaded", function () {
        LoadItinerarySearch();
    });
} else {
    // Calls the function directly in cases where the widget is rendered dynamically after 'DOMContentLoaded' has occurred
    LoadItinerarySearch();
}

function LoadItinerarySearch() {
    // hide/show proper dropdown when radio button changes
    $('.js-itinerary-type-radio').change(function () {
        var $this = $(this);
        var id = $this.attr('data-id');
        var activityRadio = $('#activity-' + id);
        var locationRadio = $('#location-' + id);

        if (activityRadio && activityRadio.length > 0 && activityRadio[0].checked) {
            $("#locationList-" + id).parent('.js-itinerary-search__item').hide();
            $("#activityList-" + id).parent('.js-itinerary-search__item').show();
        } else if (locationRadio && locationRadio.length > 0 && locationRadio[0].checked) {
            $("#locationList-" + id).parent('.js-itinerary-search__item').show();
            $("#activityList-" + id).parent('.js-itinerary-search__item').hide();
        }
    });
    // handle redirect when submit button is clicked
    $('.js-itinerary-search-submit').click(function (e) {
        e.preventDefault();
        var $this = $(this);
        var id = $this.attr('data-id');
        var baseUrl = $this.attr('data-href');
        var activityRadio = $('#activity-' + id);
        var locationRadio = $('#location-' + id);

        if (activityRadio && activityRadio.length > 0 && activityRadio[0].checked) {
            var activitySelect = $('#activityList-' + id);
            var activitySelectValue = activitySelect.find(':selected').val();
            if (activitySelectValue.length > 0) {
                window.location.href = baseUrl + "?activities=" + activitySelectValue;
            }
        } else if (locationRadio && locationRadio.length > 0 && locationRadio[0].checked) {
            var locationSelect = $('#locationList-' + id);
            var locationSelectValue = locationSelect.find(':selected').val();
            if (locationSelectValue.length > 0) {
                window.location.href = baseUrl + "?locations=" + locationSelectValue;
            }
        }
    });
}
function cardWidgetPaging(widgetIdentifier) {
    console.log(widgetIdentifier);

    var pagingGuidsInput = $("#" + widgetIdentifier + "_pagingGuidsInputTest").val();
    var currentDisplayCount = $("#" + widgetIdentifier + "_currentDisplayCountSpan").html();
    var totalRecordCountInput = $("#" + widgetIdentifier + "_totalRecordCountInputTest").val();
    var cardWidgetPropertiesTests = $("#" + widgetIdentifier + "_cardWidgetPropertiesTest").val();
    var resultsContainer = $("#" + widgetIdentifier + "_card-group__list");
    var apiUrl = '/manuallycuratedcardpaging';

    $.ajax({
        url: apiUrl,
        data: {
            pagingGuidsTest: pagingGuidsInput,
            currentDisplayCount: currentDisplayCount,
            totalRecordCount: totalRecordCountInput,
            cardWidgetProperties: cardWidgetPropertiesTests
        },
        contentType: 'application/x-www-form-urlencoded',
        method: "POST",
        success: function (result) {
            //Append new results. Update counters.
            resultsContainer.append(result.View);

            $("#" + widgetIdentifier + "_currentDisplayCountSpan").html(result.NewCount);
            currentDisplayCount = result.NewCount;

            //We are at the end of the results. Hide load more.
            if (result.NewCount == result.TotalRecordCount) {
                 $("#" + widgetIdentifier + "_loadMoreResultCards").hide();
            }

        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("Status: " + textStatus); alert("Error: " + errorThrown);
        }
    });
}
if (document.readyState === "loading") {
    // Calls the function during the 'DOMContentLoaded' event, after the HTML document has been completely loaded
    document.addEventListener("DOMContentLoaded", function () {
        initializeGoogleMaps();
    });
} else {
    // Calls the function directly in cases where the widget is rendered dynamically after 'DOMContentLoaded' has occurred
    initializeGoogleMaps();
}

function initializeGoogleMaps() {
    // timeout needs to be set so when we are in page builder mode so the Widget IFrames have sufficient time to load before the Google Maps script fires.
    if (isKenticoPageBuilder != null && isKenticoPageBuilder) {
        setTimeout(function () {
            buildGoogleMapsScript(true);
        }, 1000);
    } else {
        buildGoogleMapsScript(false);
    }
}

function buildGoogleMapsScript(isPageBuilder) {
    var mapContainers = $('.js-googleMapContainer');
    // only add the Google Maps API script to the page if it contains a mapped point widget
    if (!isPageBuilder && mapContainers.length > 0) {
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "//maps.googleapis.com/maps/api/js?v=3.exp&key=AIzaSyAjbprOH5NvCl1_jkTp3BrNEGVSDbQkWhk&callback=initializeAllMaps";
        document.body.appendChild(script);
    }
}

function initializeAllMaps() {
    var mapContainers = $('.js-googleMapContainer');
    initializeMapContainers(mapContainers);
}

function initializeSingleMap(mapId) {
    if (typeof google === 'object' && typeof google.maps === 'object') {
        var mapContainers = $('.js-googleMapContainer[data-id="' + mapId + '"]');
        initializeMapContainers(mapContainers);
    }
}

function initializeMapContainers(mapContainers) {
    mapContainers.each(function () {
        var $this = $(this);
        var id = $this.attr('data-id');
        var mapDiv = $this.find('.js-googleMap');
        var mapJson = $this.find('input').val();
        var map = JSON.parse(mapJson);

        var $section = $this.parents('.js-section');
        var mapStyles = [];
        // TODO - GET BETTER MAP STYLES FROM CREATIVE
        if ($section.hasClass('-blue') || $section.hasClass('-bluetext')) {
            mapStyles = [{ "stylers": [{ "hue": "#72A7D7" }, { "saturation": 650 }] }, { "featureType": "road", "elementType": "geometry", "stylers": [{ "lightness": 50 }, { "visibility": "simplified" }] }, { "featureType": "road", "elementType": "labels", "stylers": [{ "visibility": "off" }] }];
        } else {
            mapStyles = [{ "stylers": [{ "hue": "#BF3919" }, { "saturation": 650 }] }, { "featureType": "road", "elementType": "geometry", "stylers": [{ "lightness": 50 }, { "visibility": "simplified" }] }, { "featureType": "road", "elementType": "labels", "stylers": [{ "visibility": "off" }] }];
        }
        var mapCenter = map.MapCenter;
        var mappedPointItems = map.MappedPoints;
        var bounds = new google.maps.LatLngBounds();
        var zoomLevel = parseInt(map.MapZoomLevel);
        var mapOptions = {
            center: mapCenter,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            styles: mapStyles
        };

        if (zoomLevel > 0) {
            mapOptions.zoom = zoomLevel;
        }

        // Display a map on the page
        map = new google.maps.Map(mapDiv[0], mapOptions);

        // Display multiple markers on a map
        var infoWindow = new google.maps.InfoWindow(), marker, i;

        // Loop through our array of markers & place each one on the map
        for (i = 0; i < mappedPointItems.length; i++) {
            var position = mappedPointItems[i].Coordinates;

            marker = new google.maps.Marker({
                position: position,
                map: map
            });

            if (zoomLevel == 0) {
                bounds.extend(position);
            }

            // Allow each marker to have an info window
            google.maps.event.addListener(marker,
                'click',
                (function (marker, i) {
                    return function () {
                        var infoWindowMarkup = "";
                        if (mappedPointItems[i].Title && mappedPointItems[i].Title.length > 0) {
                            infoWindowMarkup = infoWindowMarkup + "<h4>" + mappedPointItems[i].Title + "</h4>";
                        }
                        if (mappedPointItems[i].Description && mappedPointItems[i].Description.length > 0) {
                            infoWindowMarkup = infoWindowMarkup + "<p>" + mappedPointItems[i].Description + "</p>";
                        }
                        if (mappedPointItems[i].Url && mappedPointItems[i].Url.length > 0) {
                            infoWindowMarkup = infoWindowMarkup + "<p><a href='" + mappedPointItems[i].Url + "'>More Info</a></p>";
                        }
                        infoWindow.setContent(infoWindowMarkup);
                        infoWindow.open(map, marker);
                    }
                })(marker, i));
        }

        if (zoomLevel == 0) {
            // Automatically center the map fitting all markers on the screen
            map.fitBounds(bounds);
        }
    });
}
document.addEventListener("DOMContentLoaded", function () {
    // Get references to the input and anchor elements
    var email = document.getElementById("subscribeEmail");
    var subscribeLink = document.getElementById("subscribeLink");

    if (subscribeLink != null) {
        // Add a click event listener to the anchor

        subscribeLink.addEventListener("click", addEmailToNewsLetter);
        email.addEventListener("keyup", addEmailToNewsLetter);
    }
    function addEmailToNewsLetter(event) {
        if (event.type === "click" || (event.type === "keyup" && event.key === "Enter")) {
            event.preventDefault();

            var value = "Email=" + email.value; // Get the value from the input element
            var currentHref = subscribeLink.getAttribute("href"); // Get the current href
            var targetAttr = subscribeLink.getAttribute("target");

            if (currentHref.endsWith("?")) {
                var link = currentHref + value;
                window.open(link, targetAttr);
            } else {
                var link = currentHref + "?" + value;
                window.open(link, targetAttr);
            }
        }
    }
});
if (document.readyState === "loading") {
    // Calls the function during the 'DOMContentLoaded' event, after the HTML document has been completely loaded
    document.addEventListener("DOMContentLoaded", function () {
        initializeSnowReports();
    });
} else {
    // Calls the function directly in cases where the widget is rendered dynamically after 'DOMContentLoaded' has occurred
    initializeSnowReports();
}


function initializeSnowReports() {
    var snowReports = $('.js-snow-report');
    snowReports.each(function () {
        var $this = $(this);
        var radioButtons = $this.find('input:radio');
        var checkedValue = $this.find("input:radio:checked").val();
        var newSnow = $this.find('.NewSnow48');
        var baseSnow = $this.find('.SnowBase');
        if (checkedValue === "new") {
            newSnow.show();
            baseSnow.hide();
        }
        if (checkedValue === "base") {
            newSnow.hide();
            baseSnow.show();
        }
        radioButtons.on('change', function () {
            var checked = $this.find("input:radio:checked").val();
            if (checked === "new") {
                newSnow.show();
                baseSnow.hide();
            }
            if (checked === "base") {
                newSnow.hide();
                baseSnow.show();
            }
        });
    });
}
window.onresize = function () {
    var elements = document.querySelectorAll('.js-static-gmap-wrapper iframe');
    for (let i = 0; i < elements.length; i++) {
        elements[i].width = window.innerWidth;
    }
};
$(".js-video-widget").click(videoCtaText);
$(".js-vert-vid__item-link").click(videoCtaText);

function videoCtaText() {
    var $thisVideo = $(this);
    var ctaText = $thisVideo.attr('data-cta-Text');
    var ctaLink = $thisVideo.attr('data-cta-link');
    var ctaTarget = $thisVideo.attr('data-cta-target');
    var videoSidebarHeader = $thisVideo.attr('data-video-sidebar-header');
    $(".js-drawer__nav-cta-btn").html(ctaText);
    $(".js-drawer__nav-cta-btn").attr("href", ctaLink);
    $(".js-drawer__nav-cta-btn").attr("target", ctaTarget);
    if (ctaLink == "" || ctaLink == null) {
        $(".js-drawer__nav-cta-btn").css('display', 'none');
    }
    else {
        $(".js-drawer__nav-cta-btn").css('display', 'inline-block');
    }
    $(".js-drawer__thumb-nav-heading").html(videoSidebarHeader);
}
