$(document).ready(function(){
    //RWI-0547 [FX] 2023-12-21 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","" );
            // }
        });
        $(".view-less-documents").closest("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" );
            // }

        });
        $(".view-more-documents").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_carrier").val() != '' || !$("#subscriber_email").val() );
					}
				},
				subscriber_carrier: {
					required: function(element) {
						return $("#subscriber_phone").val() != '';
					}
				}
			}
		});
	}
	if($("#unsubscribe-form").length) {
		$("#unsubscribe-form").validate({
			rules:{
				subscriber_phone: {
					required: function(element) {
						return $("#subscriber_email").val() == '';
					}
				},
				subscriber_email: {
					required: function(element) {
						return $("#subscriber_phone").val() == '';
					}
				}
			}
		});
	}
	if($("#contact-form").length) {
		$("#contact-form").validate();
	}
	if($("#meter-reading-form").length) {
		$("#meter-reading-form").validate();
	}

	// payment address box
	if($("#payment-address").length) {
		$("#payment-address").detach().prependTo(".entry-content:eq(0)");
	}
	if($(".billpay-direct-link").length) {
		$(".billpay-direct-link.small").detach().appendTo("#payment-address");
	}

	if($("#google-map-wrapper").length) {
		$("#google-map-wrapper").detach().prependTo(".entry-content:eq(0)");
		gmap_initialize_map();
	}


    // ajax submit for subscribe form
    $("#subscribe-form").on('submit', function(e){
        e.preventDefault();

        $.ajax({
            type: "POST",
            url: "subscribe.html",
            data: $( "#subscribe-form" ).serialize(),
            success: function(data){
                console.log('Subscribe - success. ', data);
                $( "#modal_subscribe .modal-body" ).html( data );
                $( "#modal_subscribe .modal-footer" ).hide();
            },
            error: function(data){
                console.log('Subscribe - failure. ', data);
                $( "#modal_subscribe .modal-message" ).html( data.responseText ? data.responseText  : '<div class="alert alert-danger">Unknown error. Please try again.</div>' );
            }
        });
    });

    // ajax submit for unsubscribe form
    // RWI-0381 convert unsubscribe modal to page DC 12/02/21
    // commented out modal support in case it's needed in the future
    $("#unsubscribe-form").on('submit', function(e){
        e.preventDefault();
/*
        $( "#modal_unsubscribe .modal-message" ).html();

        if( !$(this).find("[name='subscriber_email']").val()
         && !$(this).find("[name='subscriber_phone']").val() ) {

            $( "#modal_unsubscribe .modal-message" ).html( '<div class="alert alert-danger">Please enter either an email address or a phone number.</div>' );
            return false;
        }

*/
        if( $(this).find("[name='g-recaptcha-response']").length
         && !$(this).find("[name='g-recaptcha-response']").val() ) {

//            $( "#modal_unsubscribe .modal-message" ).html( '<div class="alert alert-danger">Please check the box to prove you\'re a human.</div>' );
            $( "#form-message" ).html( '<div class="alert alert-danger">Please check the box to prove you\'re a human.</div>' );
            $("#form-message-row").removeClass("hidden");
            return false;
        }

        $.ajax({
            type: "POST",
            url: "unsubscribe.html",
            data: $( "#unsubscribe-form" ).serialize(),
            success: function(data){
//                console.log(data);
//                $( "#modal_unsubscribe .modal-body" ).html( data );
                $( "#form-message" ).html( data );
                $( '#form-message-row').removeClass("hidden");
//                $( "#modal_unsubscribe .modal-footer" ).hide();
                $( "#submit-button" ).hide();
            }
        });
    });

    // set header text position
    setTimeout(set_header_text_position,100);
    setTimeout(set_header_text_position,1000);
    $(window).on('resize',set_header_text_position);

    // 2018-04-11 [BW,JJ]
    // iOS 11 input elements in fixed modals
    var bodyPosition;
    $(document).on("show.bs.modal",function(){
        bodyPosition = $("body").css("position");
        $("body").css("position","fixed");
        $("body").css("width","100%");
    });
    $(document).on("hide.bs.modal",function(){
        $("body").css("position",bodyPosition);
        $("body").css("width",'');
    });

    // #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');
            }
        });
    });

});



/**
 * set_header_text_position  function.
 *
 * In the "masthead" (header) area, if both the image and the text box are present,
 * we check the image's width (relative to its CSS max-width).  If the image is
 * smaller than the max width, we bring the text over to the left, so that it is
 * a consistent distance away from the logo.
 *
 * @since 2018-02-26
 */
function set_header_text_position() {
    var $mb = $(".masthead-brand");
    var $mb_img = $mb.find(".masthead-brand-image");
    var $mb_txt = $mb.find(".masthead-brand-text");
    console.log('set_header_text_position()');
    if( $mb_img.length && $mb_txt.length ) {
        var img_max_width = parseInt( $mb_img.css('max-width') );

        console.log( 'found widths: '+ img_max_width + ', ' + $mb_img.outerWidth() );

        if( img_max_width && $mb_img.outerWidth() < img_max_width ) {
            console.log('moving header text');
            $mb_txt.css('left', ($mb_img.outerWidth() + 15) + 'px');
        }
    }
}



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() {
    var myOptions = {
      zoom: 7,
      mapTypeId: google.maps.MapTypeId.HYBRID
    };
    map['MS'] = new google.maps.Map(document.getElementById("google-map"),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(item_lat_array[i] && 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>");

  }
