;(function($, window, document, undefined) {
	var $win = $(window);
	var $doc = $(document);

	function initMap() {
    var map;
		var $map = $('#map');

		map = new google.maps.Map($map[0], {
			center: {
				lat: parseFloat($map.data('lat')),
				lng: parseFloat($map.data('lng'))
			},
			zoom: 16,
			scrollwheel: false,
			disableDefaultUI: true,
			zoomControl: true,
			fullscreenControl: true,
			draggable: false
		});

		var marker = new google.maps.Marker({
        position: {
				lat: parseFloat($map.data('lat')),
				lng: parseFloat($map.data('lng'))
			},
        map: map,
        title: $map.data('venue')
		});

		var infowindow = new google.maps.InfoWindow({
		maxWidth: 200,
			content: '<p>'+$map.data('venue')+'<br /><br />'+$map.data('addr')+'<br /><br /><a href="http://maps.google.com/?q='+$map.data('addr')+'">Click here for Map</a></p>'
		});

		google.maps.event.addListener(marker, 'click', function() {infowindow.open(map,marker);});
	}

	$doc.ready(function() {
		$win.on('load', function(){
			if ($('#map').length) {initMap();}
		});

		// Get variables ready
		var site_url = "https://ggsc.berkeley.edu/";
		var href = $(location).attr('href');
		var $uriArray = href.substring(site_url.length,href.length).split('/');
		var $segment1 = $uriArray[0];
		var $segment2 = $uriArray[1];

		// Apple mobile devices require a double-tap on some links to make them work. This fixes that bug
		$(".content").on("click touchend", "a", function(e) {
			var el = $(this);
			var link = el.attr("href");
			var target = el.attr("target");

			// Check that the link is not a hash link or that the object is not a tab
			// Fix 08-2017 : add check for _blank target (a link that opens in a new tab would also trigger to be loaded in the same tab)
			if (link != "#" && target != "_blank" && !el.parents(".tabs-nav").length) {
				window.location = link;
			}
		});

		// Slider
		$('.slider-services .owl-carousel').owlCarousel({
			loop: true,
			responsive: {
				0: {
					items: 1
				},
				767: {
					items: 2
				},
				900: {
					items: 3
				}
			}
		});

		var $owl = $('.slider-services .owl-carousel')

		$('.slider-prev').click(function(event) {
			$owl.trigger('prev.owl.carousel');

			event.preventDefault();
		})

		$('.slider-next').click(function(event) {
			$owl.trigger('next.owl.carousel');

			event.preventDefault();
		})

		// Mobile Menu
		$('.btn-menu').on('click', function(event) {
			$(this).toggleClass('active');
			$('.header').toggleClass('open');
			$('body').toggleClass('no-scroll');

			event.preventDefault();
		});

		// Mobile Sidebar
		if ( $('.temp-menu').is(':visible') ) {
			$('.show-menu').on('click', function(event){
				$('.temp-menu').fadeOut("200", function() {$('.full-menu').fadeIn("200");});

				event.preventDefault();
			});
		}

		// Search
		$('.search .search-trigger').on('click', function(event) {
			$(this).parents('.search').addClass('open');

			event.preventDefault();
		});

		$('.search .search-close').on('click', function(event) {
			$(this).parents('.search').removeClass('open');

			event.preventDefault();
		});

		// Nav Primary
		$('.nav-primary li a, .nav-utilities li a').each(function() {
			var href = $(this).attr('href');
			var $hrefArray = href.substring(site_url.length,href.length).split('/');
			var $hrefSegment1 = $hrefArray[0];
			var $hrefSegment2 = $hrefArray[1];
			if ($hrefSegment1 == $segment1 && ($hrefSegment2 == $segment2 || $hrefSegment2 == null)) {
				$('.nav-primary li a').each(function() {$(this).removeClass('nav-link-red');});
				$(this).addClass('nav-link-red');
			}
		});

		// Nav Primary Mobile Dropdown
		$('.nav-primary .dropdown-secondary, .nav-utilities .dropdown-secondary').each(function() {$(this).parent().addClass('has-dd');});

		$('.nav-primary > ul > .has-dd > a, .nav-utilities > ul > .has-dd > a').on('click', function(event) {
        if ($win.width() < 768) {
            var $this = $(this);
            var $parent = $this.parent();

            if (!$parent.hasClass('active')) {
                $('.nav-primary > ul > .has-dd > a, .nav-utilities > ul > .has-dd > a').parent().removeClass('active')
                setTimeout(function(){$parent.addClass('active');}, 400);
                event.preventDefault();
            }
        }
		});

		// Nav Secondary
		$('.nav-secondary .dropdown li').each(function() {
			var $this = $(this);

			if ($this.hasClass('current')) {$this.parents('.dropdown').addClass('open');}
		});

		$('.nav-secondary .dropdown').each(function() {$(this).parent().addClass('has-dropdown');});


		// Tabs and anchors linked to tab hashtag
		$('.tabs .tabs-nav a, .tab-link').on('click', function(event) {

			// prevent the anchor tags from jumping to the top of the page
			event.preventDefault();

			// get the value after the hashtag
			var link = $(this).attr('href');

			// this may not be a tab, so we need to find the tab it references
			var $this = $('.tabs').find('a[href="'+link+'"]');

			// Add the click to the history state
			if(history.pushState) {
				history.pushState(null, null, link);
			}
			else {
				location.hash = link;
			}

			$this.parent().addClass('current').siblings().removeClass('current');
			$(link).addClass('current').siblings().removeClass('current');

			if ($win.width() < 768) {
				$('html, body').animate({
					scrollTop: $('.tabs .tabs-body').offset().top
				}, 800);
			}

		});


		// Open the tab on page load
		$(".tabs-nav li a").each( function(index) {
			$hash = window.location.hash.substr(1).toLowerCase().replace(/ /g,"_");
			if (!$hash.length) {return;}
			$tab_href = $(this).attr("href").replace("#","");
			$tab_text = $(this).text().toLowerCase().replace(/ /g,"_");;

			if ($hash == $tab_text || $hash == $tab_href) {
				$(".tabs-nav li").removeClass("current");
				$(this).parent().addClass("current");
				$(".tabs-body .tab").removeClass("current");
				if ($("#"+$hash).length) {$("#"+$hash).addClass("current");} else {
					$(".tabs-body .tab").eq(index).addClass("current");
				}

			}
		});


		// make FAQ headers expandable
		$(".faq-a").hide();
		$(".faq-q").click(function() {
			$(this).next(".faq-a").toggle();
			if ( $(this).hasClass("selected") ) {$(this).removeClass("selected");} else {$(this).addClass("selected");}
		});


        // Bridging differences
        if ($segment1 === 'what_we_do' && $segment2 === 'major_initiatives' && $uriArray[2] === 'bridging_differences') {
            $(document).on('click', 'a[href*="Bridging_Differences_Playbook"]', function(event) {
                event.preventDefault();
                event.stopPropagation();

                var popupUrl = 'https://ggsc.berkeley.edu/_ajax/newsletter-bridging-popup';

                $.magnificPopup.open({
                    items: {
                        src: popupUrl,
                        type: 'ajax'
                    },
                    fixedContentPos: false,
                    callbacks: {
                        ajaxContentAdded: function() {
                            popupPos();

                            // Create a MutationObserver to watch for changes in the success response div
                            var observer = new MutationObserver(function(mutations) {
                                mutations.forEach(function(mutation) {
                                    if (mutation.type === 'childList' && mutation.target.style.display !== 'none') {
                                        // hide the skip button
                                        $('#bridging-skip-signup').hide();
                                        // Close the popup after a short delay
                                        $('#mce-success-response').append('<p class="pdf-link">The PDF should open automatically, if not, <a class="inline-link" href="' + href + '" target="_blank">click here</a>.</p>');
                                        setTimeout(function() {
                                            // Success message is displayed, trigger download
                                            window.open(href, '_blank');
                                            setTimeout(function() {$.magnificPopup.close();}, 2000);
                                        }, 2000);

                                        // Disconnect the observer
                                        observer.disconnect();
                                    }
                                });
                            });

                            // Start observing the success response div
                            observer.observe(document.getElementById('mce-success-response'), {
                                childList: true,
                                attributes: true,
                                attributeFilter: ['style']
                            });

                            // Add event listener for the skip button
                            $('#bridging-skip-signup').on('click', function(e) {
                                e.preventDefault();
                                // Trigger download of the original URL
                                window.open(href, '_blank');
                                // Close the popup
                                $.magnificPopup.close();
                            });
                        }
                    }
                });
            });
        }


		// Popup
		$('.link-popup').magnificPopup({
			type: 'ajax',
			fixedContentPos:false,
			callbacks: {
				ajaxContentAdded: function() {
					popupPos();
					/* ADRIENNE ADDED THIS BLOCK TO MAKE NESTED LINKS WORK */
					$('.secondary-popup').magnificPopup({
                        type: 'ajax',
                        fixedContentPos:false,
                        callbacks: {
                            ajaxContentAdded: function() {
                                popupPos();

                                $('a').on('click', function() {
                                    return -1;
                                });
                            }
                        }
                    });

					$('.cancel-popup').on('click',function(event) {
						event.preventDefault();
						$.magnificPopup.close();
					});
					/* END ADDED CODE */
					$('a').on('click', function() {
						return -1;
					});
					var mc1Submitted = false;

					$('#mc-embedded-subscribe').on('click',function ( event ){

						if($('input[class="mce-group"]:checked').length > 0){
							$('#reqMsg').removeClass('mce_inline_error');
							return true;
						} else {
							$('#reqMsg').addClass('mce_inline_error');

							event.preventDefault();
							window.stop();
						}
					});


					$('#mc-embedded-subscribe-form').on('submit reset', function (event) {
						if ("submit" === event.type) {
							dataLayer.push({
								'event': 'GGSCSubscriptionPopupSubmit',
								'DLV_SUBMIT':'success'
							});
						}
						else if ( "reset" === event.type && mc1Submitted ) {console.log('success');}
					});
				}
			}
		});

		function popupPos() {
			if( $win.scrollTop() < 300 ) {
				$('.mfp-bg, .mfp-wrap').css( 'top', $('.header').outerHeight() + 29 );
			}
		};

		// Load popup on third page view
		(function () {
			// create cookie
			var viewed = Cookies.get('gg_donate_popup_viewed') || 0; // viewed is 0 if its not set already
			var visited = Cookies.get('gg_visited') || 0; // visited is 0 if its not set already

            // bail on counting visits if we are on anf of the donate pages
			if ($segment1 == 'donate') {
				return false;
			}

			visited++;

			// Show on third pagevisit
			if (visited > 2 && viewed == 0) {

				// Open popup
				$('.link-popup').click(); // remove link-donation after campaign

				// increase count so it gets set and expires
				Cookies.set('gg_visited', visited, {expires: 1});

			} else if (visited < 3) {
				// set new cookie value to match visits
				Cookies.set('gg_visited', visited, {expires: 1});
				return false;
			}

			$(document).on(
				'click',
				'.mfp-close', function (e) {

				Cookies.set('gg_donate_popup_viewed', 1, {expires: 1});
			}).on('click', '.btn-donation', function (e) {
				Cookies.set('gg_donate_popup_viewed', 1, {expires: 300});
			});

		})();

		// Newsletter Signup
		// Don't submit newsletter signup if no newsletters selected
        $('#mc-embedded-subscribe').on('click', function (e) {
            //prevents newsletter check if using different mailchimp form
            if ($(this).hasClass('love-form')) {return;}
            e.preventDefault();
            if ($('#mc_embed_signup input[type=checkbox]:checked').length > 0) {
                $mc_form = $('#mc-embedded-subscribe-form');
                $mc_form.submit();
            } else {$('#mce_newsletter_checkbox_error').show();}
        });


		/**
         *
         *  Donation form scripts
         *
         **/


        // Function to control the visibility of the custom notice and uncheck 'Other' if necessary
        function updateCustomNoticeVisibility() {
            var isOtherAmountSelected = $('#banner-giving-form-amount-other').is(':checked');
            $('#custom-notice').toggle(isOtherAmountSelected);
        }

			// set donation amount when headers are clicked
		$('.donate_tier_header').on('click',function(){
			var amount = $(this).data('amount');
			// clear all the checked radio buttons that are in the fieldset of data-section="donation_amounts" and are radio buttons
			$('fieldset#donation_amounts input[type="radio"]').prop('checked', false);
			var id = '#banner-giving-form-amount-' + amount;   // get the data-amount attribute
			$(id).prop('checked', true);
		})

		// hide and disable frequency section when donation type of OneTime is selected
		$('input[name="freqtype"]').on('click',function(){
			var freqtype = $(this).val();
			if (freqtype == 'once') {
				$('fieldset[data-section="donation-frequency"]').addClass('donate-freqency-hidden');
				$('fieldset[data-section="donation-frequency"] input[type="radio"]').prop('checked', false);
				$('fieldset[data-section="donation-frequency"] input[type="radio"]').prop('disabled', true);
			} else {
				$('fieldset[data-section="donation-frequency"]').removeClass('donate-freqency-hidden');
				$('fieldset[data-section="donation-frequency"] input[type="radio"]').prop('disabled', false);
			}
		})

		$('.donate_tier_header').on('click',function(){
			var amount = $(this).data('amount');
			// clear all the checked radio buttons that are in the fieldset of data-section="donation_amounts" and are radio buttons
			$('fieldset#donation_amounts input[type="radio"]').prop('checked', false);
			var id = '#banner-giving-form-amount-' + amount;   // get the data-amount attribute
			$(id).prop('checked', true);
		})

            // Listener for changes on the 'Other' radio button
        $('#banner-giving-form-amount-other').on('change', function() {
            // If 'Other' is selected, uncheck all amt1 radio buttons
            if ($(this).is(':checked')) {
                $('input[type="radio"][name="amt1"]').prop('checked', false);
            }
            updateCustomNoticeVisibility();
        });

        // Listener for changes on the numbered amount radio buttons
        $('fieldset#donation_amounts input[type="radio"][name="amt1"]').on('change', function() {
            // If any amt1 is selected, uncheck 'Other' and hide custom notice
            $('#banner-giving-form-amount-other').prop('checked', false);
            updateCustomNoticeVisibility();
        });

        // Set donation amount when headers are clicked
        $('.donate_tier_header').on('click', function() {
            var amount = $(this).data('amount');
            // Clear all the checked radio buttons that are in the fieldset of data-section="donation_amounts" and are radio buttons
            $('fieldset#donation_amounts input[type="radio"]').prop('checked', false);
            var id = '#banner-giving-form-amount-' + amount; // get the data-amount attribute
            $(id).prop('checked', true).trigger('change'); // Trigger change event to update the visibility
        });

        // Initialize the visibility of the custom notice based on the current selection
        updateCustomNoticeVisibility();

	});
})(jQuery, window, document);


function are_cookies_enabled()
{
    var cookieEnabled = (navigator.cookieEnabled) ? true : false;

    if (typeof navigator.cookieEnabled == "undefined" && !cookieEnabled)
    {
        document.cookie="testcookie";
        cookieEnabled = (document.cookie.indexOf("testcookie") != -1) ? true : false;
    }
    return (cookieEnabled);
}

function SetCookie(c_name,value,expiredays)
{
	var exdate=new Date()
	exdate.setDate(exdate.getDate()+expiredays)
	document.cookie=c_name+ "=" +escape(value)+";path=/"+((expiredays==null) ? "" : ";expires="+exdate.toUTCString())

	//console.log('COOKIE: ' + c_name + 'created expires on ' + exdate.toUTCString());
}
function SetSubscribeCookie()
{
	SetCookie('subscribed-cookie','subscribed-cookie',365*10000);
	//console.log('NO COOKIE DETECTED! TRIGGERING SETCOOKIE FOR SUBSCRIPTION');
	$('#mc_embed_signup').slideUp();
	$('#mc_embed_signup_response').slideDown();
	setTimeout("$('#popup-container').fadeOut('slow')", 5000);
	SetCookie('subscribe-return',window.location.pathname,1);
}
function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}
function openParentingCard(){
	var isParentingPath = document.location.pathname.indexOf("/parenting/category/");
	if(isParentingPath > -1 && document.location.hash && document.location.hash != ""){
    $targetOverlayElement =  $(document.location.hash);
    if($targetOverlayElement.length > 0){
        $.magnificPopup.open({
            items: {
                src: $targetOverlayElement
            },
            mainClass: "mfp-fade mfp-modal",
			preloader: false,
			modal: true
        });
    }
	}
}
