$(document).ready(function(){
	//RWI-0547 [FX] 2023-12-11 View more & view less
	$(document).on("click",".view-more-documents",function(e){
		$(this).closest('ul').find('li').each(function(index, value) {
			if ($(this).hasClass("document-item")) {
			//	$(this).show();
				$(this).fadeIn( 200 );
			} else {
				$(this).hide();
			}
			// if (index === 3) {
			// 	$(this).css( "opacity","" );
			// }
		});
		$(this).closest('ul').find(".view-less-btn-li").show();
	});
	$(document).on("click",".view-less-documents",function(e){
		$(this).closest('ul').find('li').each(function(index, value) {
			if ($(this).hasClass("document-item") && index > 9) {
				$(this).fadeOut( 200);

			} else {
				$(this).show();
			}
			// if (index === 3) {
			// 	$(this).css( "opacity","0.4" );
			// }

		});
		$(this).closest('ul').find(".view-more-btn-li").closest("li").show();
		$(this).closest("li").hide();
	});
	// validation
	if($("#subscribe-form").length) {
		$("#subscribe-form").validate({
			rules:{
				subscriber_email: {
					required: function(element) {
						return $("#subscriber_phone").val() == '';
					}
				},
				subscriber_phone: {
					required: function(element) {
						return ( !$("#subscriber_email").val() );
					}
				}
			}
		});
	}
	if($("#unsubscribe-form").length) {
		$("#unsubscribe-form").validate({
			rules:{
				subscriber_phone2: {
					required: function(element) {
						return $("#subscriber_email").val() == '';
					}
				},
				subscriber_email: {
					required: function(element) {
						return $("#subscriber_phone2").val() == '';
					}
				}
			}
		});
	}

	// hide alerts for this user (for this session)
	$("#site_alerts .close").on('click', function(){
		console.log("closing alerts...");
		$.ajax({
			type: "POST",
			url: '/dismiss_alert.html',
			data: 'dismiss=1',
			success: function scs(data){
				console.log("dismissed alert, ", data);
			}
		});
	});

	// show automatic alert
	if($("#modal_alert_automatic").length) {
		var alertModal = new bootstrap.Modal(document.getElementById('modal_alert_automatic'));
		alertModal.show();
		$("#modal_alert_automatic").on("hide.bs.modal",function(e) {
			// dismiss and store in session
			console.log("hiding automatic modal.");
			$.ajax({
				url:   "/dismiss_alert.html"
				,type: "POST"
				,data: {
					alert_id: $(this).attr("data-alert-id")
				}
			});
		});
	}

	// payment address box
	if($("#payment-address").length) {
		$("#payment-address").detach().insertAfter("#site_main h1:eq(0)");
	}
	if($(".billpay-direct-link").length) {
		$(".billpay-direct-link.small").detach().appendTo("#payment-address");
	}

	if($("#google-map").length) {
		$("#google-map").detach().prependTo(".entry-content:eq(0)");
		gmap_initialize_map();
	}


	///////////////////////////////////////////////////////////////////////
	// primary nav links are triggers only
	$('#navprimary ul.level1 > li > a.parentlink').on('click', function() {
    return false;
	});
	// show/hide responsive nav dropdown
	$('#navprimary a.navlabel').on('click', function() {
    var href = $.attr(this, 'href');
		if ($(href).hasClass('closed')) {
			$('#navprimary .level1').removeClass('open').addClass('closed');
			$(href).removeClass('closed').addClass('open');
		}	else {
			$(href).removeClass('open').addClass('closed');
		}
    return false;
	});

	// google map
	if($("#location-map").length) {
		gmap_initialize_map("location-map");
	}

	// make video responsive (constrained to YouTube for now)
	$('#site_main iframe').each(function() {
		var iframeHeight = $(this).attr('height');
		var iframeWidth = $(this).attr('width');
		var iframeSrc = $(this).attr('src');
		if(iframeHeight && iframeWidth && iframeSrc.includes('youtube')) {
			var paddingTop = (iframeHeight / iframeWidth) * 100;
			$(this).wrap('<div class="responsive-video" style="padding-top:' + paddingTop + '%;"></div>');
		}
	});

	// #RWI-0586 [BW,JJ] Add pausible carousels
	var carouselElement = $('.carousel-pausible');
	carouselElement.each(function(){
		var $carousel = $(this);

		$carousel.find('.btn-control').click(function() {
			// carousel is playing, we will pause it
			if ($(this).attr('data-c-play') == 'true') {
				$(this).attr('data-c-play', 'false');
				$(this).find('i').toggleClass('fa-play fa-pause');
				$(this).find('.btn-control-text').text('Play Slideshow');
				$carousel.carousel('pause');
			}
			// carousel is paused, we will play it
			else {
				$(this).attr('data-c-play', 'true');
				$(this).find('i').toggleClass('fa-play fa-pause');
				$(this).find('.btn-control-text').text('Pause Slideshow');
				$carousel.carousel('cycle');
			}
		});
	});
});

// PROMO HEIGHT
$(window).on("load",function() {
	var promo_height = [];
	if ($('.carousel-inner').html()) {
		$('.carousel-item.promo').each(function() {
			promo_height.push($(this).outerHeight(true));
		});
		var biggest = Math.max(...promo_height);
		// console.log(promo_height);
		$('.carousel-inner-promo').height(biggest);
		// console.log(biggest);
	}
	else { console.log('no html'); }
	$('.invisible').removeClass('invisible');
});


function stripEOLN(formElement) {
   for(i=0; i<formElement.elements.length; i++) {
      if(formElement.elements[i].type == 'textarea') {
         formElement.elements[i].value = formElement.elements[i].value.replace(/[\r\n]/g," ");
      }
   }
}



////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////

	// Google Maps
	var map_initialized = false;
	var map = [];
    var bounds = new google.maps.LatLngBounds ();
	var geocoder;
    var infoWindow = new google.maps.InfoWindow;
    var maxZoom = 14;
	var fitBounds = true;

    function setWindowContent(index) {
    	return item_bubble_array[index];
    }

	/*
    // clear arrays
    var item_ids_array = [];
    var item_loc_array = [];
    var item_lat_array = [];
    var item_lon_array = [];
    var item_bubble_array = [];
    */


function gmap_initialize_map(element_id) {
    var myOptions = {
      zoom: 7,
      mapTypeId: google.maps.MapTypeId.HYBRID,
      mapTypeControl: true,
      zoomControl: true
    };
    map['MS'] = new google.maps.Map(document.getElementById(element_id),myOptions);

	$("body").append("<div id='gms' style='display:none'><strong>Array of size "+item_loc_array.length+"</strong></div>");
    for(i=0;i<item_loc_array.length;i++) {
        if(!isNaN(parseFloat(item_lat_array[i])) && !isNaN(parseFloat(item_lon_array[i]))) {
            showLatLon(item_lat_array[i],item_lon_array[i],'MS',true,fitBounds,i);
			$("#gms").append("<span id='debug-latlon-"+item_ids_array[i]+"'>"+" (#"+i+"):"+item_lat_array[i]+" * "+item_lat_array[i]+"</span>");
        } else {
            codeAddress(item_loc_array[i],'MS',true,fitBounds,i);
			$("#gms").append("<span id='debug-addr-"+item_ids_array[i]+"'>"+" (#"+i+"):"+item_loc_array[i]+"</span>");
        }
    }

	// RWI-0505 [WB] commented out below and moved here
	if(fitBounds) {
		google.maps.event.addListenerOnce(map['MS'], 'zoom_changed', function () {
			if (map['MS'].getZoom() > maxZoom) map['MS'].setZoom(maxZoom);
		});
	}
}

 /*
 *	The functions "codeAddress" and "showLatLon" work on the same map.
 *		"showLatLon" is used if there is a lat/lon pair present;
 *		"codeAddress" is used if not (to geocode an address).
 *		note that Google allows only a maximum (10) geocode requests per page.
 */

  function codeAddress(query,mapIndex,showMarker,fitBounds,markerIndex) {

  	if(typeof showMarker=='undefined') showMarker = true;
  	if(typeof fitBounds=='undefined') fitBounds = false;
  	if(typeof icontype=='undefined') icontype = 'member';
    var address = query;
    geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {

        bounds.extend (results[0].geometry.location);
        if(fitBounds) {
	        map[mapIndex].fitBounds (bounds);
	        /*google.maps.event.addListenerOnce(map[mapIndex], 'zoom_changed', function() {
			  if (map[mapIndex].getZoom() > maxZoom) map[mapIndex].setZoom(maxZoom);
			});*/
        } else {
        	map[mapIndex].setCenter(results[0].geometry.location);
		}

        if(showMarker) {
			var marker = new google.maps.Marker({
				map: map[mapIndex],
				position: results[0].geometry.location
			});
			google.maps.event.addListener(marker, 'click', function() {
				infoWindow.setContent(setWindowContent(markerIndex));
				infoWindow.open(map[mapIndex],marker);
			});
        }

      	$("#gms").append("<em id='debug-worked-"+markerIndex+"'>"+markerIndex+" worked: "+address+"</em>");
      } else {
      	$("#gms").append("<em id='debug-broke-"+markerIndex+"'>"+markerIndex+" unsuccessful ("+status+"): "+address+"</em>");
//        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }

  function showLatLon(qlat,qlon,mapIndex,showMarker,fitBounds,markerIndex) {

  	if(typeof showMarker=='undefined') showMarker = true;
  	if(typeof fitBounds=='undefined') fitBounds = false;
  	if(typeof icontype=='undefined') icontype = 'member';

    var myLatLng = new google.maps.LatLng(qlat, qlon);


        bounds.extend (myLatLng);
        if(fitBounds) {
	        map[mapIndex].fitBounds (bounds);
	        /*google.maps.event.addListenerOnce(map[mapIndex], 'zoom_changed', function() {
			  if (map[mapIndex].getZoom() > maxZoom) map[mapIndex].setZoom(maxZoom);
			});*/
        } else {
        	map[mapIndex].setCenter(myLatLng);
		}

        if(showMarker) {
			var marker = new google.maps.Marker({
				map: map[mapIndex],
				position: myLatLng
			});
			google.maps.event.addListener(marker, 'click', function() {
				infoWindow.setContent(setWindowContent(markerIndex));
				infoWindow.open(map[mapIndex],marker);
			});
        }

      	$("#gms").append("<em id='debug-latlon-"+markerIndex+"'>"+markerIndex+" worked: "+qlat+"/"+qlon+"</em>");

  }

