PageSourceSearch

https://aerc.org/wp-content/themes/aerc/js/main.js?ver=6.7

js aerc.org collected 2026-09-24 20:17:03 UTC 175,761 bytes, 4,929 lines download raw bytes

1////Global Variable Declaration
2//var base64Img = null;
3//margins = {
4//  top: 70,
5//  bottom: 40,
6//  left: 30,
7//  width: 550
8//};
9///* append other function below: */
10//generate = function()
11//{
12//	
13//  var pdf = new jsPDF('p', 'pt', 'a4');
14//  pdf.setFontSize(18);
15//  pdf.fromHTML(document.getElementById('record'), 
16//    margins.left, // x coord
17//    margins.top,
18//    {
19//      // y coord
20//      width: margins.width// max width of content on PDF
21//    },function(dispose) {
22//      headerFooterFormatting(pdf)
23//    }, 
24//    margins);
25//    
26//  var iframe = document.createElement('iframe');
27//  iframe.setAttribute('style','position:absolute;right:0; top:0; bottom:0; height:100%; width:650px; padding:20px;');
28//  document.body.appendChild(iframe);
29//  
30//  iframe.src = pdf.output('datauristring');
31//};
32var call_flag = 1;
33(function($) {
34	
35	/* VARIABLES */
36    var $document = $(document);
37	var $cuerpo = $('body');
38	var $ventana = $(window);
39	var $widthVentana = $ventana.width();
40	var $htmlcuerpo = $('html, body');
41	var $img_lazy = $('.lazy');
42
43    /*----------------------------------------------------------------------------------*/
44    /* Lazy Images
45    /*----------------------------------------------------------------------------------*/
46    lazy();
47    function lazy(){
48        $img_lazy.lazy(0, function(){
49            $(this).on('load',function(){
50                $(this).addClass('loaded');
51            });
52        });
53    }
54
55
56    /*----------------------------------------------------------------------------------*/
57    /* SumoSelect
58    /*----------------------------------------------------------------------------------*/
59//    var $select = $('select');
60//    createSumoSelect($select);
61//
62//    function createSumoSelect(element){
63//        if((element).length > 0) {
64//            $(element).SumoSelect();
65//        }
66//    }
67    //createSumoSelect('select');
68
69    /*-----------------------------------------------------------------------------------*/
70    /* Sliders
71    /*----------------------------------------------------------------------------------*/
72
73    var $owl_welcome = $("#slider_welcome");
74    if( $owl_welcome.length ){
75        $owl_welcome.owlCarousel({
76            items: 1,
77            loop: true,
78            smartSpeed: 630,
79            autoplay: true,
80            startPosition: 1,
81            autoplayTimeout: 5480,
82            mouseDrag: false,
83            lazyLoad : true,
84            animateOut: 'fadeOut',
85            center: true,
86            startPosition: 0,
87            rewindNav : true
88        });
89    }
90
91    var $owl_desintaion = $("#destination-slider");
92    if( $owl_desintaion.length ){
93	$owl_desintaion.owlCarousel({
94	    items: 1,
95	    loop: true,
96	    smartSpeed: 630,
97	    autoplay: true,
98	    startPosition: 1,
99	    autoplayTimeout: 5480,
100	    mouseDrag: true,
101	    lazyLoad : true,
102	    center: true,
103	    startPosition: 0,
104	    rewindNav : true
105	});
106    }
107    
108    var $owl_desintaion = $("#text-slider");
109    if( $owl_desintaion.length ){
110	$owl_desintaion.owlCarousel({
111	    items: 1,
112	    loop: true,
113	    smartSpeed: 630,
114	    autoplay: true,
115	    startPosition: 1,
116	    autoplayTimeout: 5480,
117	    mouseDrag: true,
118	    lazyLoad : true,
119	    center: true,
120	    startPosition: 0,
121	    rewindNav : true
122	});
123    }
124    
125    var $slider_experiences = $("#slider_experiences");
126    if( $slider_experiences.length ){
127        $slider_experiences.owlCarousel({
128            items: 2,
129            loop: true,
130            smartSpeed: 630,
131            autoplay: true,
132            autoplayTimeout: 5000,
133            mouseDrag: true,
134            lazyLoad : true,
135            rewindNav : true,
136
137            margin:20,
138            responsiveClass:true,
139            responsive:{
140                0:{
141                    items:1,
142                    margin: 0,
143                    nav:true
144                },
145                600:{
146                    items:2,
147                    nav:false
148                }
149            }
150        });
151
152        $("#slider_experiences li").on('mouseenter',function(){
153            $slider_experiences.trigger('stop.owl.autoplay');
154        })
155        $("#slider_experiences li").on('mouseleave',function(){
156            $slider_experiences.trigger('play.owl.autoplay',[5480]);
157        });
158    }
159    
160    $('html body').on('click', '.find-on-page', function(){
161    	console.log('clicked');
162    	var wrapel = $(this).closest('.find-on-page-wrapper');
163    	var textel = $(wrap).find('.find-on-page-text');
164    	var findTxt = $(textel).val();
165    	console.log(findTxt);
166    	$(wrapel).each('.call-mbr-dets', function(){
167    		if($(this).is(':contains("'+findTxt+'")')) {
168    			alert('match found');
169    		}
170    	});
171    });
172    
173    var $ccCarousel = $('.cc-carousel');
174    if( $ccCarousel.length ){
175	$ccCarousel.owlCarousel({
176                items: 3,
177                loop: true,
178                center: true,
179                smartSpeed: 400,
180                autoplay: true,
181                autoplayTimeout: 3350,
182                mouseDrag: true,
183                lazyLoad : true,
184                rewindNav : true,
185                
186                margin:20,
187                responsiveClass:true,
188                responsive:{
189                    0:{
190                	items:1,
191                	margin:0,
192                	nav:false
193                    },
194                    1150:{
195                	items:3,
196                	nav:true,
197                    }
198                }
199	});
200
201	$ccCarousel.on('initialize.owl.carousell', function(e){
202	        idx = e.item.index;
203	        $('.cc-carousel .owl-item').eq(idx).addClass('owl-middle');
204	        $('.cc-carousel .owl-item').eq(idx-1).addClass('owl-left');
205	        $('.cc-carousel .owl-item').eq(idx+1).addClass('owl-right');
206	});
207	$ccCarousel.on('translate.owl.carousel', function(e){
208	    idx = e.item.index;
209	    $('.cc-carousel .owl-item.owl-middle').removeClass('owl-middle');
210	    $('.cc-carousel .owl-item.owl-left').removeClass('owl-left');
211	    $('.cc-carousel .owl-item.owl-right').removeClass('owl-right');
212	    $('.cc-carousel .owl-item').eq(idx).addClass('owl-middle');
213	    $('.cc-carousel .owl-item').eq(idx-1).addClass('owl-left');
214	    $('.cc-carousel .owl-item').eq(idx+1).addClass('owl-right');
215	});
216    }
217    $('html body').on('change', '.selectSeason', function(e){
218    	var id = aercGetUrlVars()['member_id'];
219    	var memorhorse = 'member_id';
220    	if(!id) {
221    		var url = '/membership/official-equine-record/';
222    		var id = aercGetUrlVars()['horse_id'];
223    		memorhorse = 'horse_id';
224    	}
225    	var year = $(this).find(":selected").text();
226    	var path = window.location.pathname;
227    	window.location.href = path+'?'+memorhorse+'='+id+'&season='+year;
228    });
229    
230    $('html body').on('click', '.print-info', function(e){
231    	e.preventDefault();
232    	window.print();
233    });
234    if($('#printable').length) {
235    	var url = '/membership/official-record/'
236    	var id = aercGetUrlVars()['member_id'];
237    	var memorhorse = 'member_id';
238    	if(!id) {
239    		var url = '/membership/official-equine-record/';
240    		var id = aercGetUrlVars()['horse_id'];
241    		memorhorse = 'id';
242    	}
243    	var season = aercGetUrlVars()['season'];
244    	$('#printable').load(url+'?'+memorhorse+'='+id+'&season='+season+' #record');
245    }
246
247    function aercGetUrlVars(){
248        var vars = [], hash;
249        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
250        for(var i = 0; i < hashes.length; i++)
251        {
252            hash = hashes[i].split('=');
253            vars.push(hash[0]);
254            vars[hash[0]] = hash[1];
255        }
256        return vars;
257    }
258    $('.slick-centered .gwr').slick({
259	  infinite: true,
260	  slidesToShow: 2,
261	  slidesToScroll: 1,
262
263	  responsive: [
264	    {
265	      breakpoint: 768,
266	      settings: {
267	        slidesToShow: 1,
268	        slidesToScroll: 1,
269	      }
270	    },
271	  ]
272	});
273	$('.states-more-less label').hide();
274	$('.states-more-less label:nth-child(n+1):nth-child(-n+3)').show();
275	$('.statesLess').hide();
276	$('.statesMore').click(function(){
277		$(this).closest('.states-more-less').find('label').show();
278		$('.statesMore').hide();
279		$('.statesLess').show();
280	});
281	$('.statesLess').click(function(){
282	 	$('.states-more-less label').hide();
283    	$('.states-more-less label:nth-child(n+1):nth-child(-n+3)').show();
284		$('.statesMore').show();
285		$('.statesLess').hide();
286	});
287//    $('.slick-centered .gwr').slick({
288//	  centerMode: true,
289//	  centerPadding: '100px',
290//	  slidesToShow: 3,
291//	  responsive: [
292//	    {
293//	      breakpoint: 768,
294//	      settings: {
295//	        arrows: false,
296//	        centerMode: true,
297//	        centerPadding: '40px',
298//	        slidesToShow: 3
299//	      }
300//	    },
301//	    {
302//	      breakpoint: 480,
303//	      settings: {
304//	        arrows: false,
305//	        centerMode: true,
306//	        centerPadding: '40px',
307//	        slidesToShow: 1
308//	      }
309//	    }
310//	  ]
311//	});
312//    var $slider_book = $('#slider_book');
313//    if( $slider_book.length ){
314//        $slider_book.owlCarousel({
315//            items: 3,
316//            loop: true,
317//            smartSpeed: 630,
318//            autoplay: false,
319//            autoplayTimeout: 5000,
320//            mouseDrag: true,
321//            lazyLoad : true,
322//            rewindNav : true,
323//
324//            margin:10,
325//            responsiveClass:true,
326//            responsive:{
327//                0:{
328//                    items:1,
329//                    nav:true
330//                },
331//                600:{
332//                    items:2,
333//                    nav:false
334//                },
335//                768:{
336//                    items:3,
337//                    nav:false
338//                }
339//            }
340//        });
341//    }
342
343    var $slider_nature = $('.slider-temp');
344    if( $slider_nature.length ){
345        $slider_nature.owlCarousel({
346            items: 3,
347            loop: true,
348            smartSpeed: 630,
349            autoplay: false,
350            autoplayTimeout: 5000,
351            mouseDrag: true,
352            lazyLoad : true,
353            rewindNav : true,
354
355            margin:40,
356            responsiveClass:true,
357            responsive:{
358                0:{
359                    items:1,
360                    nav:true
361                },
362                600:{
363                    items:2,
364                    nav:false
365                },
366                768:{
367                    items:3,
368                    nav:false
369                }
370            }
371        });
372    }
373    
374    var $slider_nature = $('.aerc_slider');
375    if( $slider_nature.length ){
376	$slider_nature.owlCarousel({
377	    items: 6,
378	    loop: true,
379	    smartSpeed: 630,
380	    autoplay: false,
381	    autoplayTimeout: 5000,
382	    mouseDrag: true,
383	    lazyLoad : true,
384	    rewindNav : false,
385	    
386	    margin:40,
387	    responsiveClass:true,
388	    responsive:{
389		0:{
390		    items:3,
391		    nav:true
392		},
393		
394		600:{
395		    items:5,
396		    nav:false
397		},
398		768:{
399		    items:5,
400		    nav:false
401		},
402		1020:{
403		    items:6,
404		    nav:false
405		}
406	    }
407	});
408    }
409
410
411    var $slider = $('.slider_resort-n, .slider_resort');
412    if( $slider.length ){
413	$slider.on('initialized.owl.carousel', function(event) {
414	        var items = event.item.count;
415	        var $owlControls = $slider.find('div.owl-nav');
416
417	        items <= 1 ? $owlControls.hide() : $owlControls.show();
418
419	        switch(items){
420	            case 1:
421	        	$slider.addClass('single-items');
422	                break;
423	            case 2:
424	        	$slider.addClass('two-items');
425	                break;
426	            default:
427	        	$slider.addClass('multiple-items');
428	                break;
429	        }
430
431	    })
432	
433        $slider.owlCarousel({
434            items: 1,
435            loop: true,
436            smartSpeed: 630,
437            autoplay: false,
438            autoplayTimeout: 5000,
439            mouseDrag: true,
440            lazyLoad : true,
441            rewindNav : true
442        });
443    }
444
445    var $ListImgExperiences = $('.list-img-experiences');
446    if( $ListImgExperiences.length ){
447        $ListImgExperiences.owlCarousel({
448            items: 6,
449            loop: true,
450            smartSpeed: 630,
451            autoplay: false,
452            autoplayTimeout: 5000,
453            mouseDrag: true,
454            lazyLoad : true,
455            rewindNav : true,
456            responsive:{
457                0:{
458                    items:1
459                },
460                600:{
461                    items:3
462                },
463                1000:{
464                    items:6
465                }
466            }
467        });
468    }
469
470
471    var $frm_label = $('.cnt-input').find('label');
472    var $frm_input = $('.cnt-input').find('input');
473    var $frm_ta = $('.cnt-input').find('textarea');
474    
475	var $date = new Date();
476	var $year = $date.getFullYear();
477	var $output_year = $('#id_year');
478
479    var $type_text = $('.type-js');
480    var $seach_place = $('#searchPlace');
481
482
483    /*-----------------------------------------------------------------------------------*/
484    /* Focus
485    /*----------------------------------------------------------------------------------*/
486	$frm_label.on('click', function(){
487	    $(this).parent().find('input, textarea').focus();
488	});
489
490	$frm_input.on("focus",function(event){
491	    if($(this).length && $(this).val().length){
492	    }else{
493	        $(this).closest('.cnt-input').addClass('focus');
494	    }
495	}).on("blur", function(event){
496	    if($(this).length && $(this).val().length){
497	        $(this).closest('.cnt-input').addClass('focus');
498	    }else{
499	        $(this).closest('.cnt-input').removeClass('focus');
500	    }
501	});
502	
503	$frm_ta.on("focus",function(event){
504	    if($(this).length && $(this).val().length){
505	    }else{
506		$(this).closest('.cnt-input').addClass('focus');
507	    }
508	}).on("blur", function(event){
509	    if($(this).length && $(this).val().length){
510		$(this).closest('.cnt-input').addClass('focus');
511	    }else{
512		$(this).closest('.cnt-input').removeClass('focus');
513	    }
514	});
515
516
517    /*-----------------------------------------------------------------------------------*/
518    /* Load Section
519    /*----------------------------------------------------------------------------------*/
520    var $animation_elements = $('.toload');
521
522    function check_if_in_view() {
523        var window_height = $ventana.height();
524        var window_top_position = $ventana.scrollTop();
525        var window_bottom_position = (window_top_position + window_height) - 50;
526
527        $.each($animation_elements, function() {
528            var $element = $(this);
529            var element_height = $element.outerHeight();
530            var element_top_position = $element.offset().top;
531            var element_bottom_position = (element_top_position + element_height);
532            if ((element_bottom_position >= window_top_position) && (element_top_position < window_bottom_position)) {
533                $element.addClass('loaded').removeClass('toload');
534            } else {
535                $element.removeClass('loaded');
536            }
537        });
538    }
539    $ventana.on('scroll resize', check_if_in_view);
540    $ventana.trigger('scroll');
541
542
543    /*-----------------------------------------------------------------------------------*/
544    /* Acordeon Expand
545    /*----------------------------------------------------------------------------------*/
546    function acordeonExpand(element,parent){
547        var clicked = $(element);
548        var condition = false;
549        clicked.click(function(event) {
550            event.preventDefault();
551            $(this).addClass('actived');
552            if(condition != true){
553                $(this).addClass('actived');
554                condition = true;
555            }
556            else{
557                clicked.removeClass('actived');
558                condition = false;
559            }
560            $(this).parent().find(parent).stop(false).slideToggle();
561            $(this).parent().find(parent).toggleClass('actived');
562        });
563        $ventana.on('load', function() {
564            if (window.matchMedia('(max-width: 600px)').matches){
565                clicked.eq(0).trigger('click');
566            }
567    	});
568    }
569    acordeonExpand('.w-accordion h3','ul');
570
571
572    /*----------------------------------------------------------------------------------*/
573    /* Fecha footer
574    /*----------------------------------------------------------------------------------*/
575	$output_year.text($year);
576
577
578    /*-----------------------------------------------------------------------------------*/
579    /* Tabs Content
580     /*----------------------------------------------------------------------------------*/
581    $('.head-tab ul li a').click(function(event){
582        event.preventDefault();
583        $('.tabs a').removeClass('head-active');
584        $(this).addClass('head-active');
585        var id = $(this).data('id');
586        $('.content-tabs .item-tab').removeClass('tab-active');
587        $('#'+id).addClass('tab-active');
588        lazy();
589    });
590    $('.item-tab:first').addClass('tab-active');
591
592    /*-----------------------------------------------------------------------------------*/
593    /* Sticky Header
594    /*-----------------------------------------------------------------------------------*/
595    var $headerSite = $("#header");
596    if ($headerSite.length) {
597        var $headerSiteHeight = $headerSite.height();
598        $ventana.scroll(function() {
599            var $scrollSize = $ventana.scrollTop();
600            if ($scrollSize > $headerSiteHeight) {
601                //$headerSite.addClass('sticky');
602            } else {
603                //$headerSite.removeClass('sticky');
604            }
605        })
606    }
607
608
609    /*-----------------------------------------------------------------------------------*/
610    /* Back to Top
611    /*-----------------------------------------------------------------------------------*/
612    var $backToTop = $('#back-to-top');
613    if ($backToTop.length) {
614        var scrollTrigger = 100, // px
615            backToTop = function () {
616                var scrollTop = $(window).scrollTop();
617                if (scrollTop > scrollTrigger) {
618                    $backToTop.addClass('show');
619                } else {
620                    $backToTop.removeClass('show');
621                }
622            };
623        backToTop();
624        $ventana.on('scroll', function () {
625            backToTop();
626        });
627        $backToTop.on('click', function (event) {
628            event.preventDefault();
629            $('html,body').animate({
630                scrollTop: 0
631            }, 700);
632        });
633    }
634
635	$('.xlsDownload').click(function(e){
636		e.preventDefault();
637		var action = $(this).attr('href');
638		$.get(action, function(ret){
639			var res = ret.data.map(function(item) {
640			  return Object.values(item);
641			});
642			var result = res.map(function(item) {
643			  return Object.values(item);
644			});
645			
646			console.log(result);
647			var xls = new XlsExport(result, String);
648				xls.exportToXLS(ret.name);
649		});
650	})
651
652    /*-----------------------------------------------------------------------------------*/
653    /* simpleWeather
654    /*-----------------------------------------------------------------------------------*/
655
656    /*$.simpleWeather({
657    	location: 'Cancun, Mexico',
658    	woeid: '',
659    	unit: 'f',
660    	success: function(weather) {
661          	html = '<article class="wcontent"><h2>Current Weather</h2><p>Cancun, Mexico</p><i class="icon-'
662            +weather.code+
663            '"></i> <strong>'
664            +weather.temp+
665            '</strong>&deg;<span><strong>'
666            +weather.units.temp+
667            '</strong></span></article>';
668    		$("#weather").html(html);
669    	},
670    	error: function(error) {
671    		$("#weather-1").html('<p>'+error+'</p>');
672    	}
673    });*/
674
675
676
677    /*-----------------------------------------------------------------------------------*/
678    /* AUTOCOMPLETE
679    /*-----------------------------------------------------------------------------------*/
680	$.ui.autocomplete.prototype._resizeMenu = function () {
681	  var ul = this.menu.element;
682	  ul.outerWidth(this.element.outerWidth());
683	}
684	$('html body').on('focus', '.autocomplete-from-data', function(){
685		let types = $(this).data('types');
686		$(this).autocomplete({
687			source: types.split(','),
688			minLength: 0,
689			autoFocus: true
690		}).focus(function(){
691			$(this).autocomplete("search");
692		});
693	});
694    $('html body').on('focus', '.autocomplete#user_switch_ac', function(){
695	    $(this).autocomplete({
696		  source: '/wp-admin/admin-ajax.php?action=aerc_switch_users',
697		  minLength: 1, 
698		  autoFocus: true,
699		  select: function(e, ui) {
700		      if(ui.item.details) {
701			  $('#user_switch_selected').html(ui.item.details);
702		      }
703		    }
704	    }).focus(function () {
705		  $(this).autocomplete("search");
706	    });
707    });
708/*
709* autocomplete enter a member id
710*/
711    $('html body').on('focus', '.autocomplete.get_member_name', function(){
712	var myself = $(this);
713	var otherEL = $(this).closest('.aerc-lookup').find('.get_member_id');	
714	var wrapper = $(this).closest('.fill-after-autocomplete');
715	var distance = $(this).closest('#ride_results_form').find('#distance').children("option:selected"). val();
716	$(this).autocomplete({
717	    source: '/wp-admin/admin-ajax.php?action=aerc_autocomplete_member_id',
718	    minLength: 2, 
719	    autoFocus: true,
720	    select: function(e, ui) {
721		var memberID = ui.item.value;
722		//adding  new get var
723		$.get('/wp-admin/admin-ajax.php?action=aerc_get_member_name&idisid=1&member_id='+memberID+'&distance_id='+distance, function(data){
724  		      if(data.error){
725  			      $(myself).closest('.cnt').find('.error-msg').text(data.error).show();
726    			  $(myself).val('');
727    			  setTimeout(function(){
728    			  $(myself).closest('.cnt').find('.error-msg').hide();
729    			  },5000);
730		      }else{
731    		      if(data.name) {
732							// console.log(data);
733            			$(otherEL).val(data.name);
734            			$(wrapper).find('.fill-street').val(data.street);
735            			$(wrapper).find('.fill-city').val(data.city);
736            			$(wrapper).find('.fill-zip').val(data.zip);
737            			$(wrapper).find('.fill-state').val(data.state);
738            			$(wrapper).find('.fill-country').val(data.country);
739            			$(wrapper).find('.fill-phone').val(data.phone);
740            			$(wrapper).find('.fill-email').val(data.email);
741            			$(wrapper).find('.fill-division').val(data.division);
742            			    // $(wrapper).find('.fill-division')[0].sumo.reload();
743            			$(wrapper).find('.fill-pay-status').text(data.paystatus);
744            //			  	  $(otherEL).autocomplete("search");  			 
745            		    }
746    		      }
747		});
748	    }
749	}).focus(function () {
750	    $(this).autocomplete("search");
751	});
752    });
753/*
754** autocomplete owners name
755/*
756	
757* autocomplete enter a name
758*/
759    $('html body').on('focus', '.autocomplete.get_member_id', function(){
760	var myself = $(this);
761	var otherEL = $(this).closest('.aerc-lookup').find('.get_member_name');
762	var wrapper = $(this).closest('.fill-after-autocomplete');
763	var distance = $(this).closest('#ride_results_form').find('#distance').children("option:selected"). val();
764	//$('#division').removeAttr('tabindex').val('');
765        $(this).autocomplete({
766    	  source: '/wp-admin/admin-ajax.php?action=aerc_autocomplete_member_name',
767    	  minLength: 3,   
768          autoFocus: true, 
769    	  select: function(e, ui) {
770    		  var id = ui.item.id;
771    		  $.get('/wp-admin/admin-ajax.php?action=aerc_get_member_id&idisid=1&id='+id+'&distance_id='+distance, function(data){
772    		      if(data.error){
773    			  $(myself).closest('.cnt').find('.error-msg').text(data.error).show();
774    			  $(myself).val('');
775    			  setTimeout(function(){
776    			  $(myself).closest('.cnt').find('.error-msg').hide();
777    			  },5000);
778	    			  
779    		      }else{
780        		      if(data.member_id) {
781						  $(otherEL).val(data.member_id);
782						  $(wrapper).find('.fill-street').val(data.street);
783						  $(wrapper).find('.fill-city').val(data.city);
784						  $(wrapper).find('.fill-zip').val(data.zip);
785						  $(wrapper).find('.fill-country').val(data.country);
786						  $(wrapper).find('.fill-phone').val(data.phone);
787						  $(wrapper).find('.fill-email').val(data.email);
788						  $(wrapper).find('.fill-division').val(data.division);
789						  $(wrapper).find('.fill-state').val(data.state);
790						  //$(wrapper).find('.fill-division')[0].sumo.reload();
791						  $(wrapper).find('.fill-pay-status').text(data.paystatus);
792			//		  	  $(otherEL).autocomplete("search"); 
793						 // $('#division').prop('tabindex', '-1');
794						//  $('#horseID').focus();
795						//  $('.non-member').hide();
796        		      }			  
797    		      }
798
799    		  });
800    	    }
801        }).focus(function () {
802    	  $(this).autocomplete("search");
803        });    
804    });
805    $('html body').on('focus', '.autocomplete.get_horse_name', function(){
806	var myself = $(this);
807    	var wrapper = $(this).closest('.fill-after-autocomplete');    
808	var distance = $(this).closest('#ride_results_form').find('#distance').children("option:selected"). val();
809    	$(this).autocomplete({
810    		source: '/wp-admin/admin-ajax.php?action=aerc_autocomplete_horse_id',
811    		minLength: 2,
812	    	autoFocus: true,
813    		select: function(e, ui) {
814    			var horseID = ui.item.value;
815    			var id = ui.item.id;
816	    		autoFocus: true,
817    			$.get('/wp-admin/admin-ajax.php?action=aerc_get_horse_name&horse_id='+horseID+'&distance_id='+distance, function(data){
818    	    		      if(data.error){
819    	    			$(myself).closest('.cnt').find('.error-msg').text(data.error).show();
820    	    			  $(myself).val('');
821    	    			  setTimeout(function(){
822    	    			$(myself).closest('.cnt').find('.error-msg').hide();
823    	    			  }, 5000);
824    	    		      }else{
825    				if(data.name) {
826						$(myself).closest('.aerc-rr-block').find('.horse_name').val(data.name);
827    				}
828    	    		      }
829    			});
830    			$.get('/wp-admin/admin-ajax.php?action=aerc_get_owner_name&horse_id='+horseID, function(data){
831    				if(data.name) {
832						$(myself).closest('.aerc-rr-block').find('.owner_id').val(data.member_id);
833						$(myself).closest('.aerc-rr-block').find('.owner_name').val(data.name);
834    				}
835    			});
836    		}
837    	}).focus(function () {
838    		$(this).autocomplete("search");
839    	});
840    });
841    $('html body').on('focus', '.autocomplete.get_horse_id', function(){
842	var myself = $(this);
843    	var wrapper = $(this).closest('.fill-after-autocomplete'); 
844	var distance = $(this).closest('#ride_results_form').find('#distance').children("option:selected"). val();   
845	    $(this).autocomplete({
846	        source: '/wp-admin/admin-ajax.php?action=aerc_autocomplete_horse_name',
847	        minLength: 3,
848	    	autoFocus: true,
849	    	  select: function(e, ui) {
850	    		  var horseID = ui.item.horse_id;
851	    		  var id = ui.item.id;
852	    			$.get('/wp-admin/admin-ajax.php?action=aerc_get_horse_id&id='+id+'&distance_id='+distance, function(data){
853	    	    		      if(data.error){
854	    	    			$(myself).closest('.cnt').find('.error-msg').text(data.error).show();
855	    	    			  $(myself).val('');
856	    	    			  setTimeout(function(){
857	    	    			$(myself).closest('.cnt').find('.error-msg').hide();
858	    	    			  },5000);
859	    	    		      }else{
860	    				if(data.horse_id) {
861	    					$(myself).closest('.aerc-grid').find('.horse_id').val(data.horse_id);
862	    				}
863	    	    		      }
864	    			});
865	    			$.get('/wp-admin/admin-ajax.php?action=aerc_get_owner_name&horse_id='+horseID, function(data){
866	    				if(data.name) {
867							$(myself).closest('.aerc-rr-block').find('.owner_id').val(data.member_id);
868							$(myself).closest('.aerc-rr-block').find('.owner_name').val(data.name);
869	    				}
870	    			});
871	    	    }
872	    }).focus(function () {
873	        $(this).autocomplete("search");
874	    });
875    });
876    $('.get_horse_name').change(function(){
877		var horseID = $(this).val();
878		$.get('/wp-admin/admin-ajax.php?action=aerc_get_horse_name&horse_id='+horseID, function(data){
879  		      if(data.error){
880  			$(myself).closest('.cnt').find('.error-msg').text(data.error).show();
881    			  $(myself).val('');
882    			  setTimeout(function(){
883    			  $(myself).closest('.cnt').find('.error-msg').hide();
884    			  },5000);
885    		      }else{
886			if(data.name) {
887				$('#horse_name').val(data.name);
888			}
889    		      }
890		});
891		$.get('/wp-admin/admin-ajax.php?action=aerc_get_owner_name&horse_id='+horseID, function(data){
892		    if(data.name) {
893		    	$('#ownerID').val(data.member_id);
894		    	$('#owner-name').val(data.name);
895		    }
896		});
897    });
898    
899    $('.region_search').click(function(e){
900			e.preventDefault();
901			var form = $(this).closest('form').serialize();
902			$('.dirctory-results .cnt').html('<h1 style="text-align: center;"  class="spinnerSearch"><i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i><br />Click only once - hold your horses!</h1>');
903			$.post('/wp-admin/admin-ajax.php?action=aerc_region_search', form, function(data){
904					$('.dirctory-results .cnt').html(data.html);
905					if(data.html == '<div class=\"aerc-three-grid\"><\/div>') {
906						$('.dirctory-results .cnt').text('Sorry, nothing matched your search request. Please consider expanding your search.!');
907					}
908			});
909			var scrollto = $('.dirctory-results').offset().top - 250;
910						$('html,body').animate({
911								scrollTop: scrollto
912						}, 700);
913				});
914    $('.dirctory_search').click(function(e){
915		e.preventDefault();
916		var form = $(this).closest('form').serialize();
917		$('.dirctory-results .cnt').html('<h1 style="text-align: center;"  class="spinnerSearch"><i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i><br />Click only once - hold your horses!</h1>');
918		$.post('/wp-admin/admin-ajax.php?action=aerc_directory_search', form, function(data){
919				$('.dirctory-results .cnt').html(data.html);
920				if(data.html == '<div class="aerc-three-grid"></div>') {
921					$('.dirctory-results .cnt').text('Sorry, nothing matched your search request. Please consider expanding your search.!');
922				}
923		});
924		var scrollto = $('.dirctory-results').offset().top - 250;
925					$('html,body').animate({
926							scrollTop: scrollto
927					}, 700);
928			});
929
930    $('.member_horse_lookup_name').click(function(e){
931		e.preventDefault();
932		var form = {
933			'name' : $("#name").val(),
934			'equine' : ''
935		};
936		$('.dirctory-results .cnt').html('<h1 style="text-align: center;"><i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i><br />Click only once - hold your horses!</h1>');
937		$.post('/wp-admin/admin-ajax.php?action=aerc_memeber_horse_lookup_ajax', form, function(data){
938			$('.dirctory-results .cnt').html(data.html);
939		});
940		var scrollto = $('.dirctory-results').offset().top - 250;
941		$('html,body').animate({
942			scrollTop: scrollto
943		}, 700);
944    });
945
946	$('.member_horse_lookup_equine').click(function(e){
947		e.preventDefault();
948		var form = {
949			'name' : '',
950			'equine' : $("#equine").val()
951		};
952
953		$('.dirctory-results .cnt').html('<h1 style="text-align: center;"><i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i><br />Click only once - hold your horses!</h1>');
954		$.post('/wp-admin/admin-ajax.php?action=aerc_memeber_horse_lookup_ajax', form, function(data){
955			$('.dirctory-results .cnt').html(data.html);
956		});
957		var scrollto = $('.dirctory-results').offset().top - 250;
958		$('html,body').animate({
959			scrollTop: scrollto
960		}, 700);
961    });
962
963    $('.regional_vet_lookup').click(function(e){
964	e.preventDefault();
965	var form = $(this).closest('form').serialize();
966	$.post('/wp-admin/admin-ajax.php?action=aerc_regional_vet_list_ajax', form, function(data){
967	    $('.dirctory-results .cnt').html(data.html);
968	});
969	var scrollto = $('.dirctory-results').offset().top - 250;
970	$('html,body').animate({
971	    scrollTop: scrollto
972	}, 700);
973    });
974    $('.paid_member').click(function(e){
975	e.preventDefault();
976	var form = $(this).closest('form').serialize();
977	$('.dirctory-results .cnt').html('<h1 style="text-align: center;"><i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i><br />Click only once - hold your horses!</h1>');
978	const region_code_int = $('select[name="region"]').val();
979
980	const regionCode = [{code: 1, name :'Central'}, {code: 2, name:'Midwest'} ,{code :3, name :'Mountain'}, {code: 7, name: 'Northeast'}, {code: 8, name: 'Northwest'}, {code : 9, name: 'Pacific Southwest'}, {code : 10, name :'Southeast'}, {code: 11, name: 'Southwest'}, {code : 12, name: 'West'}, {code : 13, name: 'International – outside U.S. or Canada'}, {code: 14, name :'Unknown'},];
981
982	const mappedRegionCode = regionCode.map(data => {
983		if(data.code == region_code_int) {
984			return data.name;
985		}
986	});
987	$('.dirctory-results .cnt').html('<h1 style="text-align: center;"><i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i><br />Click only once - hold your horses!</h1>');
988	$.post('/wp-admin/admin-ajax.php?action=aerc_paid_member_form', form, function(data){
989			$('.dirctory-results .cnt').html(data.html);
990			$('.region_name_generate').text(`Member current dues status for the ${mappedRegionCode.join("")} region.`);
991	});
992	var scrollto = $('.dirctory-results').offset().top - 250;
993	$('html,body').animate({
994	    scrollTop: scrollto
995	}, 700);
996    });
997    $('.ride_results_filter').click(function(e){
998		e.preventDefault();
999		var form = $(this).closest('form').serialize();
1000		$('.dirctory-results .cnt').html('<h1 style="text-align: center;"><i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i><br />Click only once - hold your horses!</h1>');
1001		$.post('/wp-admin/admin-ajax.php?action=ride_results_filter', form, function(data){
1002			$('.dirctory-results .cnt').html(data.html);
1003		});
1004		var scrollto = $('.dirctory-results').offset().top - 250;
1005		$('html,body').animate({
1006			scrollTop: scrollto
1007		}, 700);
1008    });
1009    
1010    $('html body').on('blur', '#finish-time', function(){
1011    	var distance = $(this).closest('#ride_results_form').find('#distance').find('option:selected').data('distance');
1012		    	
1013    	var warndiv = $(this).closest('.form-column').find('.warning');
1014    	var time = $(this).val();
1015    	var forrt = $(this).closest('#ride_results_form').find('#calc_type').val();
1016    	var holdtime = '00:00';
1017    	var starttime = '00:00';
1018    	if(forrt == 'ft') {
1019    		holdtime = $(this).closest('#ride_results_form').find('#hold-time').val();
1020    		starttime = $(this).closest('#ride_results_form').find('#start-time').val();
1021    	}
1022    	
1023
1024		//does this value have a colon at the end?
1025		if(time.endsWith(':'))
1026		{
1027			time = time.slice(0, -1);
1028			$(this).val(time);
1029		}
1030
1031    	$(warndiv).text('');
1032    		if(ret.ot){
1033    			$(warndiv).text('Over Time');
1034
1035    	        $('#finish_code').val(4);
1036//    	        $('#finish_code').select2().trigger('change');
1037    		}
1038    });
1039    $('html body').on('change', '#finish_code', function(){
1040	var thisval = $(this).val();
1041	if(thisval != '1') {
1042	    $('#finish-time').val('00:00:00');
1043	}
1044    });
1045
1046    /*-----------------------------------------------------------------------------------*/
1047    /* MAP
1048    /*-----------------------------------------------------------------------------------*/
1049
1050    var flex_map_mini_view = $("#map");
1051    if (flex_map_mini_view.length) {
1052        var myLatLng2 = {
1053            lat: parseFloat(flex_map_mini_view.data('lat')),
1054            lng: parseFloat(flex_map_mini_view.data('lng'))
1055        };
1056
1057        var miniMap = new google.maps.Map(document.getElementById('map'), {
1058            zoom: 12,
1059            center: myLatLng2,
1060            mapTypeId: google.maps.MapTypeId.ROADMAP,
1061            mapTypeControl: false,
1062            streetViewControl: false,
1063            scrollwheel: false,
1064            styles: [
1065                {
1066                    "featureType": "administrative",
1067                    "elementType": "labels.text.fill",
1068                    "stylers": [
1069                        {
1070                            "color": "#444444"
1071                        }
1072                    ]
1073                },
1074                {
1075                    "featureType": "landscape",
1076                    "elementType": "all",
1077                    "stylers": [
1078                        {
1079                            "color": "#f2f2f2"
1080                        }
1081                    ]
1082                },
1083                {
1084                    "featureType": "poi",
1085                    "elementType": "all",
1086                    "stylers": [
1087                        {
1088                            "visibility": "off"
1089                        }
1090                    ]
1091                },
1092                {
1093                    "featureType": "road",
1094                    "elementType": "all",
1095                    "stylers": [
1096                        {
1097                            "saturation": -100
1098                        },
1099                        {
1100                            "lightness": 45
1101                        }
1102                    ]
1103                },
1104                {
1105                    "featureType": "road.highway",
1106                    "elementType": "all",
1107                    "stylers": [
1108                        {
1109                            "visibility": "simplified"
1110                        }
1111                    ]
1112                },
1113                {
1114                    "featureType": "road.arterial",
1115                    "elementType": "labels.icon",
1116                    "stylers": [
1117                        {
1118                            "visibility": "off"
1119                        }
1120                    ]
1121                },
1122                {
1123                    "featureType": "transit",
1124                    "elementType": "all",
1125                    "stylers": [
1126                        {
1127                            "visibility": "off"
1128                        }
1129                    ]
1130                },
1131                {
1132                    "featureType": "water",
1133                    "elementType": "all",
1134                    "stylers": [
1135                        {
1136                            "color": "#46bcec"
1137                        },
1138                        {
1139                            "visibility": "on"
1140                        }
1141                    ]
1142                }
1143            ]
1144        });
1145
1146        var marker = new google.maps.Marker({
1147            position: myLatLng2,
1148            map: miniMap
1149            /*
1150            ,
1151            icon:'../images/marker.png'
1152            */
1153        });
1154        $(document).ready(function() {
1155        	
1156
1157            $(window).resize(function() {
1158                google.maps.event.trigger(map, 'resize');
1159            });
1160            google.maps.event.trigger(map, 'resize');
1161        });
1162
1163    }
1164
1165
1166
1167
1168    /*-----------------------------------------------------------------------------------*/
1169    /* Modal Video
1170    /*-----------------------------------------------------------------------------------*/
1171
1172
1173    // Modal Video del Main
1174    var $cuerpo = $('body');
1175    // Videos de la sección 'Teh evolution of extraordinary'
1176    var $section_video = $('#video');
1177    if ($section_video.length) {
1178        $section_video.find('.open-video').on('click', function() {
1179            var $iframeVideo = creaIframeVideo($(this));
1180            if ( $iframeVideo ) {
1181                if ($cuerpo.width() < 768) {
1182                    $(this).parent().parent().append('<div class="video-inside">' + $iframeVideo + '<button class="close-inside"><span class="icon-close"></span></button></div>');
1183        			console.log('menor 768');
1184                } else {
1185            		$cuerpo.append('<div id="modal-video">' + $iframeVideo + '<button id="close-video"><span class="icon-close2"></span></button></div>');
1186                }
1187
1188            }
1189        });
1190        // Boton cerrar
1191        $section_video.find('.video').on('click', '.close-inside', function() {
1192            var $elParent = $(this).parent();
1193            $elParent.fadeOut();
1194            setTimeout(function() {
1195                $elParent.remove();
1196            }, 1200)
1197        });
1198    }
1199    $cuerpo.on('click', '#close-video', function() { // 2.- Boton cerrar 'modal video'
1200        var $elParent = $(this).parent();
1201        $elParent.fadeOut();
1202        setTimeout(function() {
1203            $elParent.remove();
1204        }, 1200)
1205    });
1206
1207
1208
1209    function creaIframeVideo(elBoton) {
1210        var $urlVideo = elBoton.attr('data-video');
1211        if ($urlVideo !== undefined) {
1212            var $urlVideo = $urlVideo.toString();
1213            if ($urlVideo.indexOf('youtube') !== -1 || $urlVideo.indexOf('youtu.be') !== -1) { // es un video de Youtube, EJM: https://www.youtube.com/watch?v=9RBSH7Xvn3Q
1214                var srcVideo = 'https://www.youtube.com/embed/' + $urlVideo.substring($urlVideo.length - 11, $urlVideo.length) + '?autoplay=1';
1215            } else if ($urlVideo.indexOf('vimeo') !== -1) { // es un video de Vimeo, EJM: https://vimeo.com/206418873
1216                var srcVideo = 'https://player.vimeo.com/video/' + $urlVideo.substring(($urlVideo.indexOf('.com') + 5), $urlVideo.length).replace('/', '');
1217            } else {
1218                alert('The video assigned is not from Youtube or Vimeo, remember to enter the complete link of the video in the correct format.\n - Youtube: https://www.youtube.com/watch?v=9RBSH7Xvn3Q\n - Vimeo: https://vimeo.com/206418873');
1219                return false;
1220            }
1221            return '<iframe src="' + srcVideo + '" frameborder="0" allowfullscreen></iframe>';
1222        } else {
1223            alert('No se tiene un video asignado.');
1224            return false;
1225        }
1226    }
1227
1228
1229    /*-----------------------------------------------------------------------------------*/
1230    /* Modal
1231    /*-----------------------------------------------------------------------------------*/
1232    var $call_login = $('.call-login');
1233    var $call_user_switch = $('.call_user_switch');
1234    var $call_register = $('.call-register');
1235    var $call_language = $('.call-language');
1236    var $call_search = $('.call-search');
1237    var $call_offer = $('.call-offer');
1238    var $call_privacy = $('.call-privacy a');
1239    var $call_terms = $('.call-terms a');
1240    var $call_reservation = $('.call-reservation');
1241    var $call_step2 = $('.call-step2');
1242    var $call_step3 = $('.call-step3');
1243    var $call_step4 = $('.call-step4');
1244    var $call_step5 = $('.call-step5');
1245    var $call_step6 = $('.call-step6');
1246    var $call_step7 = $('.call-step7');
1247    var $call_step8 = $('.call-step8');
1248    var $call_request = $('.call-request a');
1249    var $call_gallery = $('.call-gallery');
1250    
1251    var $modal_login = $('#mdl_login');
1252    var $user_switch = $('#mdl_switch_user');
1253    var $modal_register = $('#mdl_register');
1254    var $modal_language = $('#mdl_language');
1255    var $modal_search = $('#mdl_search');
1256    var $modal_offer = $('#mdl_offer');
1257    var $modal_privacy = $('#mdl_privacy');
1258    var $modal_terms = $('#mdl_terms');
1259    var $modal_reservation = $('#mdl_reservation');
1260    var $modal_request = $('#mdl_request');
1261    var $modal_payment_resp = $('#mdl_api_resp');
1262
1263
1264    $('html body').on('click', '.call-general', function(e){
1265	e.preventDefault();
1266	var modal = $(this).data('modal');
1267	$(modal).removeClass('desactive-modal').addClass('active-modal');
1268	$cuerpo.addClass('fixed');
1269    });
1270    
1271    $('html body').on('click', '.call-mbr-dets', function(e){
1272	e.preventDefault();
1273	var modal = $(this).data('modal');
1274	$(modal).removeClass('desactive-modal').addClass('active-modal');
1275	$cuerpo.addClass('fixed');
1276    });
1277    
1278    $call_request.on('click', function(event){
1279        event.preventDefault();
1280        $('#mdl_request').removeClass('desactive-modal').addClass('active-modal');
1281        $cuerpo.addClass('fixed');
1282    });
1283
1284    $call_gallery.on('click', function(event){
1285        event.preventDefault();
1286        $('#mdl_gallery').removeClass('desactive-modal').addClass('active-modal');
1287        $cuerpo.addClass('fixed');
1288//        Galleria.configure({
1289//            
1290//        });
1291        Galleria.run('#full-gallery');
1292    });
1293
1294	
1295
1296    $('html body').on('click', '.call-login', function(event){
1297        event.preventDefault();
1298//        console.log("click");
1299        active_modal($modal_login);
1300    });
1301    $('html body').on('click', '.call_user_switch', function(e){
1302	e.preventDefault();
1303	active_modal($user_switch);
1304    });
1305    $('.call-password-reset').on('click', function(event){
1306		event.preventDefault();
1307		active_modal($('#mdl_password_reset'));
1308    });
1309    $('.call-member-activate').on('click', function(event){
1310		event.preventDefault();
1311		active_modal($('#mdl_activate_member'));
1312    });
1313    $call_register.on('click', function(event){
1314        event.preventDefault();
1315        active_modal($modal_register);
1316    });
1317
1318    $call_language.on('click', function(event){
1319        event.preventDefault();
1320        active_modal($modal_language);
1321    });
1322
1323    $call_search.on('click', function(event){
1324        event.preventDefault();
1325        active_modal($modal_search);
1326    });
1327
1328    $call_offer.on('click', function(event){
1329        event.preventDefault();
1330        active_modal($modal_offer);
1331    });
1332
1333
1334    $call_terms.on('click', function(event){
1335        event.preventDefault();
1336        active_modal($modal_terms);
1337    });
1338
1339    $call_privacy.on('click', function(event){
1340        event.preventDefault();
1341        active_modal($modal_privacy);
1342    });
1343
1344    $call_reservation.on('click', function(event){
1345        event.preventDefault();
1346        active_modal($modal_reservation);
1347        setTimeout(function() {
1348            active_slide($modal_reservation.find('.frm-step1'));
1349        }, 800);
1350    });
1351
1352    $call_step2.on('click', function(event){
1353        event.preventDefault();
1354        active_modal($modal_reservation);
1355        active_slide($modal_reservation.find('.frm-step2'));
1356
1357    });
1358
1359
1360    $call_step3.on('click', function(event){
1361        event.preventDefault();
1362        active_modal($modal_reservation);
1363        active_slide($modal_reservation.find('.frm-step3'));
1364
1365
1366        /*For activate to animate of calendar*/
1367//        setTimeout(function() {
1368//            $( "#date-input" ).focus();
1369//            $('body').find('.ui-datepicker-today').find('.ui-state-default').trigger('click');
1370//        }, 800);
1371
1372    });
1373
1374    $call_step4.on('click', function(event){
1375        event.preventDefault();
1376        active_modal($modal_reservation);
1377        active_slide($modal_reservation.find('.frm-step4'));
1378
1379    });
1380
1381    $call_step5.on('click', function(event){
1382        event.preventDefault();
1383        active_modal($modal_reservation);
1384        active_slide($modal_reservation.find('.frm-step5'));
1385
1386    });
1387    
1388    $call_step6.on('click', function(event){
1389	event.preventDefault();
1390	active_modal($modal_reservation);
1391	active_slide($modal_reservation.find('.frm-step6'));
1392	
1393    });
1394    
1395    $call_step7.on('click', function(event){
1396	event.preventDefault();
1397	active_modal($modal_reservation);
1398	active_slide($modal_reservation.find('.frm-step7'));
1399	
1400    });
1401
1402    $call_step8.on('click', function(event){
1403	event.preventDefault();
1404	//submit the form
1405	var formdata = $('.frm-step1, .frm-step2, .frm-step3, .frm-step4, .frm-step5, .frm-step6, .frm-step7').seri
1405alize();
1406
1407	$.post('/wp-admin/admin-ajax.php?action=sw_frm_reservation_request', formdata, function(data){
1408	    if(data.success) {
1409		active_modal($modal_reservation);
1410		active_slide($modal_reservation.find('.frm-step8'));
1411	    } else {
1412		
1413	    }
1414	});
1415    });
1416
1417    /*
1418     * payment response modal
1419     */
1420    if($modal_payment_resp.length > 0) {
1421	$modal_payment_resp.appendTo('.extra-modals');
1422	active_modal($modal_payment_resp);
1423    }
1424
1425
1426    var $chk_other = $('.chk-other');
1427    $chk_other.on('click',function(){
1428        $(this).closest('form').find('.other-request').closest('.cnt-input').toggleClass('show');
1429    });
1430
1431
1432    function active_slide( $slide ){
1433        if( $('.frm').hasClass('active-slide') ){
1434            $('.frm').removeClass('active-slide').removeClass('desactive-slide');
1435            $slide.addClass('active-slide').removeClass('desactive-slide');
1436        }
1437        else{
1438            $slide.addClass('active-slide');
1439            $slide.removeClass('desactive-slide');
1440        }
1441    }
1442
1443
1444    /*Active Modal*/
1445    function active_modal( $modal ){
1446        if( $('.modal').hasClass('active-modal') ){
1447            $('.modal').removeClass('active-modal').removeClass('desactive-modal');
1448            $modal.addClass('active-modal').removeClass('desactive-modal');
1449            //$("html, body").animate({scrollTop: 0}, 1500);
1450        }
1451        else{
1452
1453            if(!$('.modal').hasClass('show-form-actions') ){
1454                $modal.addClass('active-modal');
1455                $modal.removeClass('desactive-modal');
1456//                $cuerpo.addClass('fixed');
1457                //$("html, body").animate({scrollTop: 0}, 1500);
1458            }else{
1459                $cuerpo.addClass('full-calendar');
1460            }
1461        }
1462    }
1463
1464    /*close Modal*/
1465    $('html body').on('click', '.modal .close', function(event){
1466        var $this = $(this);
1467        var $modal = $this.closest('.active-modal');
1468		var $modalID = $modal.attr('id');
1469		var type = $('#calc_type').val();
1470		var distance = $('#distance').val()
1471		
1472		if($modalID == 'bcResults' && type){
1473			//reload the table
1474			$.get('/wp-admin/admin-ajax.php?action=ride_results_details&distance='+distance+'&type='+type, function(data){
1475			    $('#ride-results-details').html(data.html);
1476			    $('#ride_results_table').DataTable({
1477			        responsive: {
1478			            details: {
1479			                type: 'column'
1480			            }
1481			        },
1482			        columnDefs: [ {
1483			            className: 'control',
1484			            orderable: false,
1485			            targets:   0
1486			        } ],
1487			        dom: 'Bfrtip',
1488			        buttons: [
1489			            'print'
1490			        ]
1491			    } );
1492			});
1493		}
1494		$modal.removeClass('active-modal');
1495        $modal.find('.cnt-input').removeClass('focus');
1496        $modal.find('.cnt-input').find('input').val('');
1497        $modal.addClass('desactive-modal');
1498        link = [];
1499    	sessionStorage.setItem("links", JSON.stringify(links));
1500    	$('.modal-breadcrumbs').html('');
1501        setTimeout(function() {
1502            $modal.find('.frm').removeClass('active-slide');
1503            $( "#date-input" ).focusout();
1504
1505
1506            $('.wrap-choose-date').addClass('show').removeClass('hide');
1507            $('.wrap-choose-travel').addClass('hide').removeClass('show');
1508
1509        }, 800);
1510        $cuerpo.removeClass('fixed');
1511
1512    });
1513
1514    /* register */
1515    $('.btn-register').click(function(e){
1516	e.preventDefault();
1517        var username = $(this).closest('form').find('#reg_username').val();
1518        var password = $(this).closest('form').find('#reg_password').val();
1519        var password2 = $(this).closest('form').find('#reg_password2').val();
1520        var membership = $(this).closest('form').find('#reg_membership').val();
1521        
1522	$.post('/wp-admin/admin-ajax.php?action=sw_get_register', {username: username, password: password, password2: password2, membership: membership}, function(data){
1523	    if(data.success) {
1524		Cookies.set('nameOwner', data.nameOwner);
1525		Cookies.set('lastnameOwner', data.lastnameOwner);
1526		Cookies.set('username', data.username);
1527		Cookies.set('swloggedin', 'true');
1528		
1529	        $('.modal').removeClass('active-modal').removeClass('desactive-modal');
1530//	        $cuerpo.find('#header').find('.nav-member').addClass('login-default');
1531	        $cuerpo.addClass('is-login').removeClass('fixed');		
1532	        $('.logged-in-name').text(data.nameOwner);
1533	    } else {
1534		
1535	    }
1536	});
1537    });
1538    
1539    /* check login */
1540    if(Cookies.get('nameOwner')) {
1541	$('.logged-in-name').text(Cookies.get('nameOwner'));
1542	$('body').addClass('is-login');
1543    }
1544    // console.log(Cookies.get('nameOwner'));
1545    /* login */
1546    $('html body').on('click', '.btn_login', function(event){
1547        event.preventDefault();
1548        $('.login-msg').text('');
1549        // console.log('log');
1550        var username = $(this).closest('form').find('#username').val();
1551        var password = $(this).closest('form').find('#password').val();
1552        var redirectto = $(this).closest('form').find('#redirectto').val();
1553		$.post('/wp-admin/admin-ajax.php?action=sw_user_login', {username: username, password: password, redirectto: redirectto}, function(data){
1554	        $('.login-msg').text(data.message);
1555		    if(data.loggedin) {
1556			Cookies.set('nameOwner', data.nameOwner);
1557			Cookies.set('lastnameOwner', data.lastnameOwner);
1558			Cookies.set('username', data.username);
1559			Cookies.set('swloggedin', 'true');
1560			// Server decides the landing page (Member Home unless a members-only deep link);
1561			// fall back to the form's own value for older responses.
1562			window.location.href = data.redirect_to || redirectto;
1563		    } else {
1564		    	
1565		    }
1566		});
1567    });
1568    $('html body').on('click', '.btn_activate', function(event){
1569        event.preventDefault();
1570        $('.login-msg').text('');
1571        // console.log('log');
1572        var username = $(this).closest('form').find('#username').val();
1573        var password = $(this).closest('form').find('#password').val();
1574        var membernum = $(this).closest('form').find('#member_number').val();
1575		$.post('/wp-admin/admin-ajax.php?action=aerc_activate', {username: username, password: password, membernum: membernum}, function(data){
1576	        $('.login-msg').html(data.message);
1577		});
1578    });
1579    $( "#aerc_activate" ).validate({
1580	  rules: {
1581	    password: "required",
1582	    password_2: {
1583	      equalTo: "#password"
1584	    }
1585	  }
1586	});
1587    /*log out */
1588    $('.logout').click(function(e){
1589	e.preventDefault();
1590	Cookies.remove('nameOwner');
1591	Cookies.remove('lastnameOwner');
1592	Cookies.remove('username');
1593	Cookies.remove('swloggedin');
1594	$.post('/wp-admin/admin-ajax.php?action=sw_get_logout', {}, function(data){
1595	    //we aren't doing anything here
1596	});
1597	$('body').removeClass('is-login');
1598        location.href=('/');
1599    });
1600
1601    $('.pw-reset').click(function(e){
1602	$('#pw-error').text('');
1603	e.preventDefault();
1604        var username = $(this).closest('form').find('#username').val();
1605        var oldpassword = $(this).closest('form').find('#old-password').val();
1606        var newpassword = $(this).closest('form').find('#new-password').val();
1607        var newpassword2 = $(this).closest('form').find('#new-password2').val();
1608	$.post('/wp-admin/admin-ajax.php?action=sw_get_pw_reset', {username: username, oldpassword: oldpassword,newpassword: newpassword, newpassword2: newpassword2}, function(data){
1609	    if(data.success){
1610	        $('#mdl_success').removeClass('desactive-modal').addClass('active-modal');
1611	        $cuerpo.addClass('fixed');
1612	        $('#old-password, #new-password, #new-password2').val('');
1613	    } else {
1614		console.log(data.msg);
1615		$('#pw-error').text(data.msg);
1616	    }
1617	});
1618	
1619    });
1620
1621    /*-----------------------------------------------------------------------------------*/
1622    /* Boton Back modal
1623    /*-----------------------------------------------------------------------------------*/
1624    var $btnBack = $("#mdl_reservation .back");
1625    $btnBack.click(function() {
1626       $(this).parents().find(".active-slide").prev().addClass("active-slide").next().removeClass("active-slide");
1627    });
1628    
1629    /*-----------------------------------------------------------------------------------*/
1630    /* Mostrando modal en detalle de articulo
1631    /*-----------------------------------------------------------------------------------*/
1632    var $btnShowDetail = $(".item-resorts article .link");
1633    var $articleModalDetail = $(".overlay-modal-information");
1634    $btnShowDetail.click(function(){
1635        $(this).parent().find(".overlay-modal-information").addClass("active-modal");
1636    });
1637    $articleModalDetail.click(function(){
1638        $(this).removeClass("active-modal")
1639    });
1640
1641    /*-----------------------------------------------------------------------------------*/
1642    /* Tabs
1643    /*-----------------------------------------------------------------------------------*/
1644    var $navTabs = $(".nav-tabs");
1645    var $contentTabs = $(".tab-content");
1646    $navTabs.on("click",".btn-tab",function(){
1647        $navTabs.find(".btn-tab").removeClass("active");
1648        $(this).addClass("active");
1649        var $idTab = $(this).attr("data-id");
1650        $contentTabs.find(".item-tab").removeClass("active");
1651        $contentTabs.find("#"+$idTab).addClass("active");
1652    });
1653    /*-----------------------------------------------------------------------------------*/
1654    /* Resort Bloc scritp para limitar la cantidad de elemntos a mostrar + botón ver más
1655    /*-----------------------------------------------------------------------------------*/
1656    var $contentResortList = $("#resort-bloc");
1657    if ($contentResortList.length) {
1658        $contentResortList.find('.list-bloc ul').each(function() {
1659            var $totalElements = $(this).find('li').size();
1660            if($totalElements > 11){
1661                $(this).parent().addClass('show-btn-more');
1662            }
1663        });
1664    }
1665
1666    var $readMore = $("#resort-bloc .show-more");
1667    $readMore.click(function(){
1668        //console.log('activamos');
1669        //$(this).parent().toggleClass('active-list');
1670    });
1671
1672    /*-----------------------------------------------------------------------------------*/
1673    /* Mostrar sub menú responsive
1674    /*-----------------------------------------------------------------------------------*/
1675    var $responsiveMenu = $(".responsive-menu .menu-item-has-children>a");
1676    $responsiveMenu.click(function(){
1677        //$(this).parent().parent().toggleClass('active-list');
1678        //$(this).parent().toggleClass('active');
1679    });
1680
1681    var $closeResponsiveMenu = $("#close-menu-responsive");
1682    $closeResponsiveMenu.click(function(){
1683        $("body").removeClass('open-menu');
1684        $(".responsive-menu ul").removeClass('active-list');
1685        $(".responsive-menu .menu-item-has-children>a").removeClass('active');
1686    });
1687
1688    var $openResponsiveMenu = $("#open-menu-responsive");
1689    $openResponsiveMenu.click(function(){
1690        $("body").addClass('open-menu');
1691    });
1692 
1693
1694    /*-----------------------------------------------------------------------------------*/
1695    /* Change awards based on selection
1696    /*-----------------------------------------------------------------------------------*/
1697    $('select#awardResortSelect').change(function(){
1698	var resort = $(this).val();
1699	var parel = $(this).closest('section');
1700	$.post('/wp-admin/admin-ajax.php?action=sw_get_resort_award', {resortid: resort}, function(data){
1701	    $(parel).find('.awards-inner-block').html(data.html); 
1702	});
1703    });
1704 
1705    /*-----------------------------------------------------------------------------------*/
1706    /* Filter Gallery based on selection
1707    /*-----------------------------------------------------------------------------------*/
1708    $('select#galleryCategorySelect').change(function(){
1709	var cat = $(this).val();
1710	if(cat == '0'){
1711	    $('.gallery-thumb-wrapper').show('1000')
1712	}else{
1713    	        var hidden = [];
1714    	        var shown = [];
1715		$('.gallery-thumb-wrapper').each(function(){
1716		    var cats = $(this).data('cats');
1717		    if(jQuery.inArray(cat, cats) != '-1') {
1718			shown.push($(this));
1719		    }else{
1720			hidden.push($(this));
1721		    }
1722		    console.log(shown);
1723		});
1724		if(hidden.length) {
1725		    $(hidden).each(function(){
1726			$(this).hide('1500');
1727		    });
1728		}
1729		if(shown.length) {
1730		    $(shown).each(function(){
1731			$(this).show('1000');
1732		    });
1733		}
1734	}
1735    });
1736    
1737    /*
1738     * Filter Posts by Category
1739     */
1740    $('select#postsCategorySelect').change(function(){
1741	var qstring = {};
1742	var cat = $(this).val();
1743	if(cat.length){
1744	    qstring.cat = cat;
1745	}
1746	var search = $(this).data('searched');
1747	if(cat.length){
1748	    qstring.s = search;
1749	}
1750	var link = $(this).data('action')+"?"+$.param(qstring);
1751	location.href=link;
1752    });
1753    /*
1754     *Masonry  
1755     *
1756     */
1757    $(document).ready(function(){
1758        if($('.ms-item').length) {
1759            $('.loading-icon').show();
1760    	    $('#ms-container').hide();
1761    	    
1762            $(window).load(function() {
1763        	$('.loading-icon').hide();
1764                $('#ms-container').show();
1765        	      var container = document.querySelector('#ms-container');
1766        	      var msnry = new Masonry( container, {
1767        	        itemSelector: '.ms-item',
1768        	        columnWidth: '.ms-item',                
1769        	      });  
1770            });
1771        }
1772    });
1773    /*
1774     * Filter Contacts by Department
1775     */
1776    $('select#contactPhoneFilter').change(function(){
1777	var dept = $(this).val();
1778	
1779	$('.dept-info').hide();
1780	$(dept).show();
1781    });
1782    $('.nolink > a').click(function(e){
1783	e.preventDefault();
1784    });
1785    /*
1786     * One thing I noticed is that when click on any of the dropdowns, it automatically navigates you to a page, rather than allowing a user to select a dropdown option.
1787     */
1788    $('.content-responsive-menu .menu-item-has-children a').not('.sub-menu a').click(function(e){
1789	e.preventDefault();
1790    });
1791    setTimeout(function(){
1792	$('#main #slider_welcome.owl-carousel .owl-stage-outer .owl-stage .owl-item li article h2 span.strong').addClass('visible');
1793    },250);
1794    
1795    //scroll add class to body
1796    $(window).scroll(function() {
1797    	if ($(window).scrollTop() > 200) {
1798    		$('body').addClass('scrolled');
1799    	} else {
1800    		$('body').removeClass('scrolled');
1801    	}
1802	  if ($(window).scrollTop() > 800) {
1803	     $('body').addClass('big-scrolled');
1804	  } else {
1805	      $('body').removeClass('big-scrolled');
1806	  }
1807	  
1808	});
1809    
1810	/*
1811	 * Pay for the ride
1812	*/
1813    $('html body').on('submit', '#ride_results_payment', function(e){
1814		e.preventDefault();
1815    	var $this = $(this);
1816        var $modal = $this.closest('.active-modal');
1817    	if($($this).data('submitted')){
1818    		return true;
1819    	}
1820    	var returnURl = $(this).data('action');
1821    	var formData = $(this).serialize();
1822
1823  		$('body').append('<div class="pmt-wait"><div><i class="fa fa-spin fa-spinner"></i><br />Hold your horses -- we\'re processing your request! Be patient — this may take a few minutes to upload to AERC</div></div>')
1824
1825
1826		$('.submit').attr('disabled', true).addClass('disabled');
1827
1828    	$.post('/wp-admin/admin-ajax.php?action=aerc_pmt_process', formData, function(ret){
1829    		if(ret.pmterror){
1830    			$('.pmt_message').html('<h4>'+ret.pmterror+'</h4>').addClass('error').show();	
1831    			return false;
1832    		}else{
1833				var today = aercGetDateTime();
1834				
1835				$('#print-form .aerc-form').append('<input type="hidden" class="form-control" name="payment_id" value="'+ret.payment_id+'" />');
1836				$('#ride_results_payment').append('<div class="aerc-grid one" style="position: relative; z-index: 5000;"><div class="form-column"><label for="ref_code">Payment Reference ID</label><input type="text" class="form-control" name="ref_code" value="'+ret.ref_code+'" /></div></div>');
1837	      			
1838				var formPDF = createPDFofForm('submit_ride_results_pmt_complete');
1839				$('#ride_results_payment').append('<div class="aerc-grid one"><div class="form-column"></div></div>');
1840    			$($this).attr('data-submitted', true);
1841    			$('.pmt_message').html('Payment Successful!').removeClass('error').show();
1842    			setTimeout(function(){
1843	                $('html, body').animate({
1844	                    scrollTop: $($this).closest('.aerc-panel').find('.cnt').offset().top
1845	                }, 2000);
1846
1847					$('.submit').attr('disabled', false).removeClass('disabled');
1848					$($this).closest('.wpb_wrapper').find('.aerc-panel .cnt').html(formPDF.html);
1849					$($this).closest('.aerc-panel').find('.cnt').html('');
1850    				$('.pmt_message').html('').removeClass('ajax').hide();	
1851        			$modal.removeClass('active-modal');
1852        			$cuerpo.removeClass('fixed');
1853    			},2000);
1854    		}
1855    	});
1856	});
1857	
1858	$('html body').on('click', '#payByCheck', function(e){
1859		e.preventDefault();
1860		
1861    	var $this = $(this);
1862		let ride = $(this).data('ride');
1863        var $modal = $this.closest('.active-modal');
1864
1865  		$('body').append('<div class="pmt-wait"><div><i class="fa fa-spin fa-spinner"></i><br />Hold your horses -- we\'re processing your request! Be patient — this may take a few minutes to upload to AERC</div></div>')
1866	
1867		var formPDF = createPDFofForm('aerc_send_ride_to_office');
1868		$($this).append('<div class="aerc-grid one"><div class="form-column"></div></div>');
1869		
1870		$('#ride_results_payment').append('<div class="aerc-grid one"><div class="form-column"></div></div>');
1871
1872		formPDF = createPDFofForm('submit_ride_results_pmt_complete');
1873		$($this).attr('data-submitted', true);
1874		$('.pmt_message').html('Sent Successfully!').removeClass('error').show();
1875		setTimeout(function(){
1876                $('html, body').animate({
1877                    scrollTop: $($this).closest('.aerc-panel').find('.cnt').offset().top
1878                }, 2000);
1879			$($this).closest('.wpb_wrapper').find('.aerc-panel .cnt').html(formPDF.html);
1880			$($this).closest('.aerc-panel').find('.cnt').html('');
1881			$('.pmt_message').html('').removeClass('success ajax').hide();	
1882			$modal.removeClass('active-modal');
1883			$cuerpo.removeClass('fixed');
1884		},250);		
1885		/*
1886    	$.post('/wp-admin/admin-ajax.php?action=aerc_send_ride_to_office', {ride: ride}, function(ret){
1887    		$('.pmt_message').removeClass('error success');
1888    		if(ret.pmterror){
1889    			$('.pmt_message').html('<h4>'+ret.pmterror+'</h4>').addClass('error');	
1890    			return false;
1891    		}else{
1892				$('.aerc-form').append('<input type="hidden" class="form-control" name="payment_id" value="" />');
1893				$('.aerc-form').append('<div class="aerc-grid one"><div class="form-column"><label for="ref_code">Payment Reference ID</label><input type="text" class="form-control" name="ref_code" value="'+ret.ref_code+'" /></div></div>');
1894				createPDFofForm('submit_ride_results_pmt_complete');
1895    			$($this).attr('data-submitted', true);
1896    			$('.pmt_message').html('Sent Successfully!').removeClass('error');
1897    			setTimeout(function(){
1898    				$('.pmt_message').html('').removeClass('ajax');	
1899        			$modal.removeClass('active-modal');
1900        			$cuerpo.removeClass('fixed');
1901    			},4500);
1902    		}
1903    	});
1904		*/
1905	})
1906    /*
1907     * Post New Horse Form
1908     */
1909	$('html body').on('submit', '#aerc_horse_register', function(e) {
1910	  e.preventDefault();
1911	  var $this = $(this);
1912	  if (!$this.valid() || $this.data('submitted')) return;
1913	  if (!aercValidateEcheck($this)) return;
1914
1915	  // show spinner
1916	  $('body').append(
1917		'<div class="pmt-wait"><div>' +
1918		'<i class="fa fa-spin fa-spinner"></i><br />' +
1919		'Hold your horses -- processing your request!</div></div>'
1920	  );
1921	  var $btn = $this.find('.submit').attr('disabled', true).addClass('disabled');
1922	
1923	  // fetch clientKey/apiLoginID
1924	  $.getJSON('/wp-content/plugins/aercadmin/api/anet/getAuthData.php', function(auth) {
1925		var authData = {
1926		  clientKey:  auth.clientKey,
1927		  apiLoginID: auth.apiLoginID
1928		};
1929		// card OR bank (eCheck) depending on the Pay-by-Bank toggle
1930		var secureData = aercBuildSecureData($this, authData);
1931
1932		Accept.dispatchData(secureData, function(response) {
1933		  if (response.messages.resultCode === 'Ok') {
1934			// inject token fields
1935			var dv = response.opaqueData.dataValue,
1936				dd = response.opaqueData.dataDescriptor;
1937			$this
1938			  .append('<input type="hidden" name="dataValue"      value="' + dv + '" />')
1939			  .append('<input type="hidden" name="dataDescriptor" value="' + dd + '" />');
1940			// remove raw card AND bank fields before submit
1941			aercRemoveSensitivePaymentFields();
1942
1943			$this.data('submitted', true);
1944			processPaymentForm($this, 'aerc_new_equine_registration_form');
1945	
1946		  } else {
1947			// error
1948			$('.pmt-wait').remove();
1949			$btn.attr('disabled', false).removeClass('disabled');
1950			logTokenFailure({
1951				context: 'horse_register',
1952				message: response.messages.message[0].text,
1953				code: response.messages.message[0].code,
1954				page: window.location.href
1955			});
1956			$('.pmt_message')
1957			  .html('<h4>Error: ' + response.messages.message[0].text + '</h4>')
1958			  .addClass('error')
1959			  .show();
1960			setTimeout(function() {
1961			  $('.pmt_message').html('').removeClass('error ajax').hide();
1962			}, 4500);
1963		  }
1964		});
1965	  }).fail(function(){
1966		$('.pmt-wait').remove();
1967		$btn.attr('disabled', false).removeClass('disabled');
1968		logTokenFailure({
1969			context: 'horse_register',
1970			message: 'Unable to load payment configuration.',
1971			page: window.location.href
1972		});
1973		$('.pmt_message')
1974		  .html('<h4>Error: Unable to load payment configuration.</h4>')
1975		  .addClass('error')
1976		  .show();
1977	  });
1978	});
1979
1980    /*
1981     * Post Join Form
1982     */
1983	$('#aerc_join_form').validate();
1984	$('html body').on('blur', '#membership_division', function(){
1985		$(this).closest('form').validate();
1986	});
1987	
1988	// --- eCheck (Pay by Bank) helpers. Additive: when no toggle is present, or "card" is
1989	//     selected, every path below behaves exactly as the original card-only flow. ---
1990	function aercSelectedPaymentMethod($form) {
1991		var m = ($form && $form.length)
1992			? $form.find('input[name="payment_method"]:checked').val()
1993			: $('input[name="payment_method"]:checked').val();
1994		return (m === 'echeck') ? 'echeck' : 'card';
1995	}
1996	function aercBuildSecureData($form, authData) {
1997		if (aercSelectedPaymentMethod($form) === 'echeck') {
1998			return {
1999				authData: authData,
2000				bankData: {
2001					accountNumber: $('#bank_account_number').val(),
2002					routingNumber: $('#bank_routing_number').val(),
2003					nameOnAccount:  $('#bank_name_on_account').val(),
2004					accountType:    $('#bank_account_type').val()
2005				}
2006			};
2007		}
2008		return {
2009			authData: authData,
2010			cardData: {
2011				cardNumber: $('#billing_card_number').val(),
2012				month:      $('#billing_month').val(),
2013				year:       $('#billing_year').val(),
2014				cardCode:   $('#billing_cvv').val()
2015			}
2016		};
2017	}
2018	function aercRemoveSensitivePaymentFields() {
2019		$('#billing_card_number, #billing_month, #billing_year, #billing_cvv').remove();
2020		$('#bank_account_number, #bank_routing_number, #bank_name_on_account, #bank_account_type').remove();
2021	}
2022	function aercShowPmtError(msg) {
2023		$('.pmt-wait').remove();
2024		$('.pmt_message').html('<h4>' + msg + '</h4>').addClass('error').show();
2025		setTimeout(function () { $('.pmt_message').html('').removeClass('error ajax').hide(); }, 4500);
2026	}
2027	function aercValidateEcheck($form) {
2028		if (aercSelectedPaymentMethod($form) !== 'echeck') return true;
2029		var routing = ($('#bank_routing_number').val() || '').trim();
2030		var account = ($('#bank_account_number').val() || '').trim();
2031		var name    = ($('#bank_name_on_account').val() || '').trim();
2032		if (!name || !/^\d{9}$/.test(routing) || !/^\d{4,17}$/.test(account)) {
2033			aercShowPmtError('Please enter the name on the account, a 9-digit routing number, and a valid account number.');
2034			return false;
2035		}
2036		if (!$('#echeck_consent').is(':checked')) {
2037			aercShowPmtError('Please authorize the bank debit to continue.');
2038			return false;
2039		}
2040		return true;
2041	}
2042	// Toggle card vs bank. Disabling the card fields in eCheck mode keeps jQuery-validate
2043	// (which marks the card fields `required`) from blocking an eCheck submission, and keeps
2044	// them out of the serialized POST.
2045	$('html body').on('change', 'input[name="payment_method"]', function () {
2046		var echeck = $('input[name="payment_method"]:checked').val() === 'echeck';
2047		$('#aerc_bank_fields').toggle(echeck);
2048		$('#aerc_card_fields').toggle(!echeck);
2049		$('#billing_card_number, #billing_cvv, #billing_month, #billing_year').prop('disabled', echeck);
2050	});
2051
2052	$('html body').on('submit', '#aerc_renewal', function (e) {
2053		e.preventDefault();
2054	
2055		var $this = $(this);
2056	
2057		if (!$this.valid()) {
2058			return false;
2059		}
2060
2061		if (!aercValidateEcheck($this)) {
2062			return false;
2063		}
2064
2065		if (!$this.data('submitted')) {
2066			$('body').append('<div class="pmt-wait"><div><i class="fa fa-spin fa-spinner"></i><br />Hold your horses -- we\'re processing your request! Be patient — this may take a few minutes to upload to AERC</div></div>');
2067	
2068			// Fetch clientKey and apiLoginID from the server
2069			$.getJSON('/wp-content/plugins/aercadmin/api/anet/getAuthData.php', function (authData) {
2070				var clientKey = authData.clientKey;
2071				var apiLoginID = authData.apiLoginID;
2072	
2073				var authData = {
2074					clientKey: clientKey,
2075					apiLoginID: apiLoginID
2076				};
2077
2078				// card OR bank (eCheck) depending on the Pay-by-Bank toggle
2079				var secureData = aercBuildSecureData($this, authData);
2080	
2081				console.log(authData);
2082				console.log(secureData);
2083
2084				// Use Accept.js to tokenize the payment data
2085				Accept.dispatchData(secureData, function (response) {
2086					console.log(response);
2087					if (response.messages.resultCode === 'Ok') {
2088						// Tokenization successful
2089						var dataValue = response.opaqueData.dataValue;
2090						var dataDescriptor = response.opaqueData.dataDescriptor;
2091	
2092						// Add tokenized data to the form
2093						$this.append('<input type="hidden" name="dataValue" value="' + dataValue + '" />');
2094						$this.append('<input type="hidden" name="dataDescriptor" value="' + dataDescriptor + '" />');
2095	
2096						// Remove sensitive fields (card AND bank) before submitting
2097						aercRemoveSensitivePaymentFields();
2098	
2099						// Mark the form as submitted
2100						$this.data('submitted', true);
2101	
2102						// Submit the form via AJAX
2103						processPaymentForm($this, 'aerc_renewal_form');
2104					} else {
2105						// Handle tokenization errors
2106						$('.pmt-wait').remove();
2107						logTokenFailure({
2108							context: 'renewal',
2109							message: response.messages.message[0].text,
2110							code: response.messages.message[0].code,
2111							page: window.location.href
2112						});
2113						$('.pmt_message').html('<h4>Error: ' + response.messages.message[0].text + '</h4>').addClass('error').show();
2114						setTimeout(function () {
2115							$('.pmt_message').html('').removeClass('error ajax').hide();
2116						}, 4500);
2117					}
2118				});
2119			}).fail(function(){
2120				$('.pmt-wait').remove();
2121				logTokenFailure({
2122					context: 'renewal',
2123					message: 'Unable to load payment configuration.',
2124					page: window.location.href
2125				});
2126				$('.pmt_message').html('<h4>Error: Unable to load payment configuration.</h4>').addClass('error').show();
2127				setTimeout(function () {
2128					$('.pmt_message').html('').removeClass('error ajax').hide();
2129				}, 4500);
2130			});
2131		}
2132	});
2133
2134		
2135	// Function to process the form via AJAX
2136	function processPaymentForm($form, action) {
2137		// Serialize form data
2138		var formData = $form.serialize();
2139		$.post('/wp-admin/admin-ajax.php?action=aerc_pmt_process', formData, function (ret) {
2140			$('.pmt_message').removeClass('error success').hide();
2141			
2142			if (ret.pmterror) {
2143				$('.pmt-wait').remove();
2144				$('.pmt_message').html('<h4>' + ret.pmterror + '</h4>').addClass('error').show();
2145				setTimeout(function () {
2146					$('.pmt_message').html('').removeClass('error ajax').hide();
2147				}, 4500);
2148			} else {
2149				var today = aercGetDateTime();
2150	
2151				$form.append('<input type="hidden" name="payment_id" value="' + ret.payment_id + '" />');
2152				$form.append('<div class="aerc-grid one"><div class="form-column"><label for="ref_code">Payment Reference ID</label><input type="text" class="form-control" name="ref_code" value="' + ret.ref_code + '" /></div></div>');
2153	
2154				$('.pmt_message').html('Payment Successful!').addClass('success').show();
2155				postForAfterPDF(action, formData, $form, ret.payment_id);
2156			}
2157		});
2158	}
2159
2160	$('html body').on('submit', '#aerc_join_form', function (e) {
2161		e.preventDefault();
2162		var $this = $(this);
2163
2164		// Refresh fee totals + line_items_json from the current DOM before tokenizing.
2165		// Horse name inputs don't trigger recalc on type, so blank cloned rows could
2166		// otherwise leave a stale fee in grand_total. (Refunds incident 2026-05-04.)
2167		$this.find('.join-form-recalcuate').first().trigger('change');
2168
2169		// prevent double‐submit and validate
2170		if (!$this.valid() || $this.data('submitted')) {
2171			return;
2172		}
2173
2174		if (!aercValidateEcheck($this)) {
2175			return;
2176		}
2177
2178		// show spinner
2179		$('body').append(
2180		'<div class="pmt-wait"><div>' +
2181		'<i class="fa fa-spin fa-spinner"></i><br />' +
2182		'Hold your horses -- we\'re processing your request!</div></div>'
2183		);
2184
2185		// fetch clientKey/apiLoginID
2186		$.getJSON(
2187		'/wp-content/plugins/aercadmin/api/anet/getAuthData.php',
2188		function (auth) {
2189			var authData = {
2190			clientKey:  auth.clientKey,
2191			apiLoginID: auth.apiLoginID
2192			};
2193
2194			// card OR bank (eCheck) depending on the Pay-by-Bank toggle
2195			var secureData = aercBuildSecureData($this, authData);
2196
2197
2198			Accept.dispatchData(secureData, function (response) {
2199
2200			if (response.messages.resultCode === 'Ok') {
2201				// add opaque data to form
2202				var dv = response.opaqueData.dataValue;
2203				var dd = response.opaqueData.dataDescriptor;
2204				$this
2205				.append('<input type="hidden" name="dataValue"      value="' + dv + '" />')
2206				.append('<input type="hidden" name="dataDescriptor" value="' + dd + '" />');
2207
2208				// remove raw card fields (card AND bank)
2209				aercRemoveSensitivePaymentFields();
2210
2211				// mark submitted and fire off your AJAX POST
2212				$this.data('submitted', true);
2213				processPaymentForm($this, 'aerc_new_registration_form');
2214
2215			} else {
2216				$('.pmt-wait').remove();
2217				console.error('Tokenization Error:', response.messages.message[0].text);
2218				logTokenFailure({
2219					context: 'join',
2220					message: response.messages.message[0].text,
2221					code: response.messages.message[0].code,
2222					page: window.location.href
2223				});
2224				$('.pmt_message')
2225				.html('<h4>Error: ' + response.messages.message[0].text + '</h4>')
2226				.addClass('error')
2227				.show();
2228				setTimeout(function () {
2229				$('.pmt_message').html('').removeClass('error ajax').hide();
2230				}, 4500);
2231			}
2232			});
2233		}
2234		);
2235	});
2236
2237    function aercGetDateTime() {
2238        var now     = new Date(); 
2239        var year    = now.getFullYear();
2240        var month   = now.getMonth()+1; 
2241        var day     = now.getDate();
2242        var hour    = now.getHours();
2243        var minute  = now.getMinutes();
2244        var second  = now.getSeconds(); 
2245        if(month.toString().length == 1) {
2246             month = '0'+month;
2247        }
2248        if(day.toString().length == 1) {
2249             day = '0'+day;
2250        }   
2251        if(hour.toString().length == 1) {
2252             hour = '0'+hour;
2253        }
2254        if(minute.toString().length == 1) {
2255             minute = '0'+minute;
2256        }
2257        if(second.toString().length == 1) {
2258             second = '0'+second;
2259        }   
2260        var dateTime = month+'/'+day+'/'+year+' '+hour+':'+minute+':'+second;   
2261         return dateTime;
2262    }
2263    /*
2264     * Post Ride Sanction Form
2265     */
2266	$('html body').on('submit', '#aerc_sanction_ride', function(e) {
2267		e.preventDefault();
2268		var $this = $(this);
2269		if (!$this.valid() || $this.data('submitted')) return;
2270		if (!aercValidateEcheck($this)) return;
2271
2272		// show spinner
2273		$('body').append(
2274		  '<div class="pmt-wait"><div>' +
2275		  '<i class="fa fa-spin fa-spinner"></i><br />Hold your horses -- we\'re processing your request! Be patient — this may take a few minutes to upload to AERC</div></div>'
2276		);
2277		var $btn = $this.find('.submit').attr('disabled', true).addClass('disabled');
2278	  
2279		// fetch clientKey/apiLoginID
2280		$.getJSON('/wp-content/plugins/aercadmin/api/anet/getAuthData.php', function(auth) {
2281		  var authData = {
2282			clientKey:  auth.clientKey,
2283			apiLoginID: auth.apiLoginID
2284		  };
2285		  // card OR bank (eCheck) depending on the Pay-by-Bank toggle
2286		  var secureData = aercBuildSecureData($this, authData);
2287
2288		  Accept.dispatchData(secureData, function(response) {
2289			if (response.messages.resultCode === 'Ok') {
2290			  // inject token fields
2291			  var dv = response.opaqueData.dataValue,
2292				  dd = response.opaqueData.dataDescriptor;
2293			  $this
2294				.append('<input type="hidden" name="dataValue"      value="' + dv + '" />')
2295				.append('<input type="hidden" name="dataDescriptor" value="' + dd + '" />');
2296			  // remove raw card AND bank fields before submit
2297			  aercRemoveSensitivePaymentFields();
2298
2299			  $this.data('submitted', true);
2300
2301			  // now submit ride form via AJAX
2302			  var formData = $this.serialize();
2303			  $.post('/wp-admin/admin-ajax.php?action=aerc_post_ride_submit', formData, function(ret) {
2304				$('.pmt_message').removeClass('error success').hide();
2305				if (ret.pmterror) {
2306				  $('.pmt-wait').remove();
2307				  $('.pmt_message')
2308					.html('<h4>' + ret.pmterror + '</h4>')
2309					.addClass('error')
2310					.show();
2311				  $btn.attr('disabled', false).removeClass('disabled');
2312				  setTimeout(function() {
2313					$('.pmt_message').html('').removeClass('error ajax').hide();
2314				  }, 4500);
2315				} else {
2316				  // append payment_id / ref_code and generate PDF
2317				  if (ret.payment_id) {
2318					$this
2319					  .append('<input type="hidden" name="payment_id" value="' + ret.payment_id + '" />')
2320					  .append(
2321						'<div class="aerc-grid one-one"><div class="form-column">' +
2322						'<label for="ref_code">Payment ID</label>' +
2323						'<input type="text" class="form-control" name="ref_code" value="' + ret.payment_id + '" disabled />' +
2324						'</div></div>'
2325					  );
2326				  }
2327				//   createPDFofForm('aerc_post_ride_submit');
2328				    $('.pmt_message').html('Sent Successfully!').removeClass('error').show();
2329				
2330					setTimeout(function(){
2331						$('.pmt_message').html('').removeClass('success ajax').hide();
2332						$this.closest('.aerc-panel').find('.cnt').html(ret.html);
2333					},2000);
2334					
2335					$('.pmt-wait').remove();
2336				}
2337			  });
2338	  
2339			} else {
2340			  // tokenization error
2341			  $('.pmt-wait').remove();
2342			  $btn.attr('disabled', false).removeClass('disabled');
2343			  logTokenFailure({
2344				context: 'sanction_ride',
2345				message: response.messages.message[0].text,
2346				code: response.messages.message[0].code,
2347				page: window.location.href
2348			  });
2349			  $('.pmt_message')
2350				.html('<h4>Error: ' + response.messages.message[0].text + '</h4>')
2351				.addClass('error').show();
2352			  setTimeout(function() {
2353				$('.pmt_message').html('').removeClass('error ajax').hide();
2354			  }, 4500);
2355			}
2356		  });
2357		}).fail(function(){
2358		  $('.pmt-wait').remove();
2359		  $btn.attr('disabled', false).removeClass('disabled');
2360		  logTokenFailure({
2361			context: 'sanction_ride',
2362			message: 'Unable to load payment configuration.',
2363			page: window.location.href
2364		  });
2365		  $('.pmt_message')
2366			.html('<h4>Error: Unable to load payment configuration.</h4>')
2367			.addClass('error').show();
2368		  setTimeout(function() {
2369			$('.pmt_message').html('').removeClass('error ajax').hide();
2370		  }, 4500);
2371		});
2372	  });
2373
2374
2375	function logTokenFailure(payload){
2376		try {
2377			payload = payload || {};
2378			$.ajax({
2379				url: '/wp-admin/admin-ajax.php',
2380				type: 'POST',
2381				data: $.extend({ action: 'aerc_log_token_failure' }, payload)
2382			});
2383		} catch (e) {}
2384	}
2385    $('.duplicate_distance').click(function(e){
2386	e.preventDefault();
2387	var dupWrapper = $(this).parent().prev();
2388	var clone = dupWrapper.clone();
2389	var oldID = $(clone).data('i');
2390	clone.insertAfter(dupWrapper).each(function(i, fields){
2391	        // Loop over data-fields groups and grab their index
2392	        $('.distancepair', fields).each(function(){
2393	                // Rename first array value from name to group index
2394	                $(this).attr('name', $(this).attr('name').replace(oldID, oldID+1)); 
2395	            });
2396	    });
2397	$(clone).attr('data-i', oldID+1);
2398    });
2399    $('.distancepair').not('.resanction-form').each(function(){
2400		var i = $(this).closest('.sanction-distance-group').data('i');
2401		var name = $(this).attr('name')+'-'+i;
2402		 $(this).attr('name', name); 
2403		});
2404    $('html body').on('click', '.clone-distance', function(e){
2405		e.preventDefault();
2406		var oldButton = $(this);
2407		var dupWrapper = $(this).closest('.sanction-distance-group');
2408		var clone = dupWrapper.clone();
2409		var oldID = $(clone).data('i');
2410		clone.insertAfter(dupWrapper).each(function(i, fields){
2411		        // Loop over data-fields groups and grab their index
2412		        $('.distancepair', fields).each(function(){
2413		                // Rename first array value from name to group index
2414		                $(this).attr('name', $(this).attr('name').replace(oldID, oldID+1)); 
2415						if($(this).hasClass('distancedistance') || $(this).hasClass('distancetype')) {
2416							$(this).val('');
2417						}
2418		            });
2419		    });
2420		$(clone).attr('data-i', oldID+1);
2421		$(clone).addClass('cloned-group').prepend('<div class="remove-row" title="remove">
2421<i class="fa fa-trash"></i></div>');
2422		$(oldButton).hide();
2423    });
2424    $('.timefilter').mask("00:00:00");
2425    $('.timeentry').mask("00:00:00");
2426    $('html body').on('keydown', '.timeentry, .timefilter', function(e){
2427		//your code
2428		if(e.keyCode != 8 && (this.value.length === 2)) {
2429			this.value += ":";
2430		}
2431		//collapse double colons
2432		if(this.value.endsWith("::")) {
2433			this.value=this.value.replace(/:+/g,":");
2434		}
2435});
2436//    $('.ridetime').mask("00:00:00");
2437//    $('.finishtime').mask("00:00:00 AA");
2438    setTimeout(function(){
2439    
2440        $('.mhi-row').each(function(){
2441        	var maxHeight = 0;
2442        	$(this).find('.vc_single_image-img').each(function(){
2443        	    maxHeight = maxHeight > $(this).height() ? maxHeight : $(this).height();
2444        	});
2445        	$(this).find('.vc_single_image-wrapper').height(maxHeight);
2446            });
2447    }, 500);
2448
2449	function createPDFofForm(action){
2450		// window.jsPDF = window.jspdf.jsPDF;
2451		    
2452		//     this.printElement = document.getElementById('print-form');
2453		// 	$('h3').addClass('pdf-print');
2454		// 	$('#print-form').addClass('save_form_reset');
2455		// 	$('.show-on-print').show();
2456		//      html2canvas(this.printElement, {
2457		// 	    ignoreElements: function( element ) {
2458			        
2459		// 	        /* Remove element with id="MyElementIdHere" */
2460		// 	        //if( 'MyElementIdHere' == element.id ) {
2461		// 	           // return true;
2462		// 	        //}
2463			        
2464		// 	        /* Remove all elements with class="MyClassNameHere" */
2465		// 	        if( element.classList.contains( 'do-not-save' ) ) {
2466		// 	            return true;
2467		// 	        }
2468			        
2469		// 	    }			
2470		// 	 }).then(canvas => {
2471				
2472		// 	  var imgData = canvas.toDataURL('image/png');
2473		
2474		//       /*
2475		//       Here are the numbers (paper width and height) that I found to work. 
2476		//       It still creates a little overlap part between the pages, but good enough for me.
2477		//       if you can find an official number from jsPDF, use them.
2478		//       */
2479		//       var imgWidth = 210; 
2480		//       var pageHeight = 295;  
2481		//       var imgHeight = canvas.height * imgWidth / canvas.width;
2482		//       var heightLeft = imgHeight;
2483		
2484		//       var doc = new jsPDF('p', 'mm');
2485		//       var position = 0;
2486		
2487		//       doc.addImage(imgData, 'WEBP', 0, position, imgWidth, imgHeight, 'temp', 'FAST');
2488		//       heightLeft -= pageHeight;
2489		
2490		//       while (heightLeft >= 0) {
2491		//         position = heightLeft - imgHeight;
2492		//         doc.addPage();
2493		//         doc.addImage(imgData, 'WEBP', 0, position, imgWidth, imgHeight, 'temp', 'FAST');
2494		//         heightLeft -= pageHeight;
2495		//       }
2496
2497		// 	var out = doc.output();
2498        //     var url = 'data:application/pdf;base64,' + btoa(out);
2499	    //       $.post('/wp-admin/admin-ajax.php?action=aerc_save_pdf', {pdf: url}, function(ret){
2500		// 			$('#print-form').find('.aerc-form').append('<input type="hidden" name="pdf_id" value="'+ret.pdfid+'" />');
2501		// 			$('#print-form').find('.aerc-form').append(ret.timestamp);
2502		//   			$('h3').removeClass('pdf-print');
2503		// 			$('#print-form').removeClass('save_form_reset');
2504			
2505					postForAfterPDF(action, $('#print-form').find('.aerc-form').serialize(), $('#print-form').find('.aerc-form'));
2506		// 	  });
2507				
2508	    //   }).catch(err=>{
2509		// 	console.log(err);
2510		// });
2511		// 	$('.show-on-print').hide();
2512	}
2513    function postForAfterPDF(action, formData, form, payment_id) {
2514		//add the payment_id to the form
2515		if(payment_id) {
2516			formData += '&payment_id='+payment_id;
2517		}
2518		
2519		//post the form
2520		$.post('/wp-admin/admin-ajax.php?action='+action, formData, function(ret){
2521			
2522			if(ret.pmterror){
2523				$('.pmt_message').html('<h4>'+ret.pmterror+'</h4>').addClass('error').show();
2524				
2525				$(form).show();	
2526				
2527				$('.pmt-wait').remove();
2528				setTimeout(function(){
2529					$('.pmt_message').html('').removeClass('error ajax').hide();	
2530				},4500);
2531			} else {
2532				$('.pmt_message').html('<h4>Form Submission Successful!</h4>').addClass('success').show();
2533				
2534				setTimeout(function(){
2535					$('.pmt_message').html('').removeClass('success ajax').hide();
2536					$(form).closest('.aerc-panel').find('.cnt').html(ret.html);
2537				},2000);
2538				
2539				$('.pmt-wait').remove();
2540			}
2541
2542		});
2543    }
2544
2545
2546	$('html body').on('click', '.modal-print', function(){
2547		let xref = $(this).data('id');
2548		createPDFFromModal(xref);
2549	});
2550
2551	function createPDFFromModal(xref){
2552		window.jsPDF = window.jspdf.jsPDF;
2553		    
2554		    this.printElement = document.getElementById(xref);
2555		     html2canvas(this.printElement, {
2556			    ignoreElements: function( element ) {
2557			        
2558			        /* Remove element with id="MyElementIdHere" */
2559			        //if( 'MyElementIdHere' == element.id ) {
2560			           // return true;
2561			        //}
2562			        
2563			        /* Remove all elements with class="MyClassNameHere" */
2564			        if( element.classList.contains( 'do-not-save' ) ) {
2565			            return true;
2566			        }
2567			        
2568			    }			
2569			 }).then(canvas => {
2570				
2571			  var imgData = canvas.toDataURL('image/png');
2572		
2573		      /*
2574		      Here are the numbers (paper width and height) that I found to work. 
2575		      It still creates a little overlap part between the pages, but good enough for me.
2576		      if you can find an official number from jsPDF, use them.
2577		      */
2578		      var imgWidth = 210; 
2579		      var pageHeight = 295;  
2580		      var imgHeight = canvas.height * imgWidth / canvas.width;
2581		      var heightLeft = imgHeight;
2582		
2583		      var doc = new jsPDF('p', 'mm');
2584		      var position = 0;
2585		
2586		      doc.addImage(imgData, 'WEBP', 0, position, imgWidth, imgHeight, 'temp', 'FAST');
2587		      heightLeft -= pageHeight;
2588		
2589		      while (heightLeft >= 0) {
2590		        position = heightLeft - imgHeight;
2591		        doc.addPage();
2592		        doc.addImage(imgData, 'WEBP', 0, position, imgWidth, imgHeight, 'temp', 'FAST');
2593		        heightLeft -= pageHeight;
2594		      }
2595
2596			doc.output('dataurlnewwindow');
2597			
2598	      });
2599	}
2600
2601
2602	$('html body').on('submit', '#aerc_horse_edit', function(e){
2603		e.preventDefault();
2604		var formData = $(this).serialize();
2605		var container = $(this).closest('.cnt');
2606		$.post('/wp-admin/admin-ajax.php?action=aerc_equine_update_form', formData, function(ret){
2607			console.log(ret.html);
2608			$(container).html(ret.html);
2609		});
2610	});
2611    $('.load-via-ajax').each(function(){
2612    	var $this = $(this);
2613    	var toload = $(this).data('load');
2614//    	$(this).load('/wp-admin/admin-ajax.php?action='+toload);
2615    	$.get('/wp-admin/admin-ajax.php?action='+toload, function(ret){
2616    		if(ret.html) {
2617    			$($this).html(ret.html);
2618    		}
2619    	});
2620    });
2621    if($('.vc_tta-panel').hasClass('vc_active')) {
2622	$('.vc_tta-panel').removeClass('vc_active');
2623    }
2624	$(window).resize(function(){
2625		mobileMenu();
2626	});
2627	mobileMenu();
2628	function mobileMenu(){
2629		//add class to nav-wrapper too so that fixed menu can be overridden
2630		if ($(window).width() < 768) {
2631	   		$('.menu-main-navigation-container').addClass('aerc-mobile-menu');
2632			if(!$('.m-menu nav').hasClass('mobile-menu')){
2633		   		$('.m-menu nav').addClass('mobile-menu');
2634		   		$('.m-menu nav li.menu-item-has-children > a').append('<i class="fa fa-chevron-circle-down mobile-menu-more"></i>');
2635		   		$('.nav-wrapper').addClass('mobile-nav');
2636			}
2637		}
2638		else {
2639		   $('.m-menu nav').removeClass('mobile-menu');
2640		   $('.mobile-menu-more').remove();
2641		   $('.nav-wrapper').removeClass('mobile-nav');
2642		}
2643		
2644	}
2645    $('.header-mobile-nav-trigger').click(function(e){
2646        e.preventDefault();
2647       $('header nav').toggleClass('active');
2648    });
2649    $(".aerc-mobile-menu .menu-item.menu-item-has-children .mobile-menu-more").click(function(){
2650	    var li = $(this).closest('li.menu-item');
2651        if($(li).hasClass('active')) {
2652			$(li).removeClass('active');
2653            $('.menu-item').removeClass('active');
2654        } else {
2655          $(li).siblings('.active').removeClass('active');
2656          $(li).addClass("active");
2657        }
2658    });
2659    $('html body').on('click', '.bcResultsModal', function(e){
2660		e.preventDefault();
2661		var modal = '#bcResults';
2662		$(modal).removeClass('desactive-modal').addClass('active-modal');
2663		$cuerpo.addClass('fixed');  
2664		$(modal).find('.more-rows').hide();
2665    });
2666    //ride resutls
2667    $('#calc_type').change(function(){
2668	var type = $(this).val();
2669	if(type == 'ft') {
2670	    $('#finish-time').removeClass('ridetime');
2671	    $('#finish-time').addClass('finishtime');
2672	    $('.ft-show').show();
2673	    $(this).closest('.aerc-grid').addClass('one-one-one-one-two').removeClass(' one-one-one-three');
2674	    $('#finishorride').text('Time');
2675	}else{
2676	    $('#finish-time').removeClass('finishtime');
2677	    $('#finish-time').addClass('ridetime');
2678	    $('.ft-show').hide();
2679	    $(this).closest('.aerc-grid').addClass('one-one-one-three').removeClass(' one-
2679one-one-one-two');
2680	    $('#finishorride').text('Time');
2681	}
2682	$('#ride-results-entry, #starter_finishers').show();
2683    });
2684    $('html body').on('blur', '.update_starters_finishers', function(){
2685	$('#ride-results-details').html('<div style="text-align: center; font-size: 36px;"><i class="fa fa-circle-o-notch fa-spin result-loading"></i></div>');
2686	var distance = $('#distance option:selected').data('distanceid');
2687	var val = $(this).val();
2688	var type = $(this).data('type');
2689	$.post('/wp-admin/admin-ajax.php?action=ride_results_update_distance', {distance: distance, value: val, type: type}, function(ret){
2690	    if(type == '') {
2691		
2692	    }
2693	    if(type == '') {
2694		
2695	    }
2696	});
2697	$('#ride_results_form #distance').find('option:selected').attr('data-'+type, val);
2698	$('#ride_results_form #distance').find('option:selected').data(type, val);
2699	$('#ride-results-details').html('<div style="text-align: center; font-size: 36px;"><i class="fa fa-circle-o-notch fa-spin result-loading"></i></div>');
2700	$.get('/wp-admin/admin-ajax.php?action=ride_results_details&distance='+distance+'&type='+type, function(data){
2701	    $('#ride-results-details').html(data.html);
2702	    $('.ride-results-page-details').show(); 
2703	    $('#ride_results_table').DataTable({
2704	        responsive: {
2705	            details: {
2706	                type: 'column'
2707	            }
2708	        },
2709	        columnDefs: [ {
2710	            className: 'control',
2711	            orderable: false,
2712	            targets:   0
2713	        } ],
2714	        dom: 'Bfrtip',
2715	        buttons: [
2716	            'print'
2717	        ]
2718	    } );
2719	});
2720    });
2721    $('#ride_results_table').DataTable( {
2722        responsive: {
2723            details: {
2724                type: 'column'
2725            }
2726        },
2727        columnDefs: [ {
2728            className: 'control',
2729            orderable: false,
2730            targets:   0
2731        } ],
2732        dom: 'Bfrtip',
2733        buttons: [
2734            'print'
2735        ]
2736    });
2737	$('html body').on('change', '#distanceCancelled', function(){
2738		let isChecked = 0;
2739		if($(this).is(':checked')) {
2740			isChecked = 1;
2741		}
2742		var distance = $('#starters').data('distance');
2743		var type = $('#calc_type').val();
2744		
2745		$.post('/wp-admin/admin-ajax.php?action=aerc_distance_cancelled', {distance: distance, value: isChecked}, function(){
2746			$.get('/wp-admin/admin-ajax.php?action=ride_results_details&distance='+distance+'&type='+type, function(data){
2747			    $('#ride-results-details').html(data.html);
2748			    $('#ride_results_table').DataTable({
2749			        responsive: {
2750			            details: {
2751			                type: 'column'
2752			            }
2753			        },
2754			        columnDefs: [ {
2755			            className: 'control',
2756			            orderable: false,
2757			            targets:   0
2758			        } ],
2759			        dom: 'Bfrtip',
2760			        buttons: [
2761			            'print'
2762			        ]
2763			    } );
2764			});
2765		});
2766	});
2767    $('html body').on('change', '#ride_results_form #distance', function(){
2768//    $('#ride_results_form #distance').change(function(){
2769		var time = $(this).find('option:selected').data('time');
2770		var holdtime = $(this).find('option:selected').data('holdtime');
2771		var starters = $(this).find('option:selected').data('starters');
2772		var finishers = $(this).find('option:selected').data('finishers');
2773		var juniors = $(this).find('option:selected').data('juniors');
2774		var distance = $(this).find('option:selected').data('distanceid');
2775		var cancelled = $(this).find('option:selected').data('cancelled');
2776		var type = $('#calc_type').val();
2777		var ischecked = '';
2778		$('#start-time').val(time);
2779		$('#hold-time').val(holdtime);
2780		$('#starters').val(starters);
2781		$('#starters').attr('data-distance', distance);
2782		$('#finishers').val(finishers);
2783		$('#finishers').attr('data-distance', distance);
2784		$('#juniors').val(juniors);
2785		$('#juniors').attr('data-distance', distance);
2786		$('#ride-results-entry, #starter_finishers').show();
2787		$('#ride-results-details').html('<div style="text-align: center; font-size: 36px;"><i class="fa fa-circle-o-notch fa-spin result-loading"></i></div>');
2788		$('#rr-ind-results-wrapper').load('/membership/ride-results #rr-ind-results');
2789	    $('.ride-results-page-details').show(); 
2790
2791		if(starters == 0) {
2792			if(cancelled == 1) {
2793				ischecked = 'checked';
2794			}
2795			$('#starters').closest('div').find('label').html('Starters<div><input type="checkbox" id="distanceCancelled" name="cancelled" value="1" '+ischecked+' /><sup style="font-size: 9px;">Check here if there were zero starters</sup></div>');
2796		} else {
2797			$('#starters').closest('div').find('label').html('Starters');
2798		}
2799
2800		$.get('/wp-admin/admin-ajax.php?action=ride_results_details&distance='+distance+'&type='+type, function(data){
2801		    $('#ride-results-details').html(data.html);
2802		    $('#ride_results_table').DataTable({
2803		        responsive: {
2804		            details: {
2805		                type: 'column'
2806		            }
2807		        },
2808		        columnDefs: [ {
2809		            className: 'control',
2810		            orderable: false,
2811		            targets:   0
2812		        } ],
2813		        dom: 'Bfrtip',
2814		        buttons: [
2815		            'print'
2816		        ]
2817		    } );
2818		});
2819    });
2820	$('html body').on('keydown', '#memberID', function(event){
2821		//don't do anything if the tab is pressed
2822		if(event.keyCode != 9 && event.keyCode != 16) {
2823			$('#member-name').val('');
2824		}
2825	});
2826	$('html body').on('keydown', '#member-name', function(event){
2827		//don't do anything if the tab is pressed
2828		if(event.keyCode != 9 && event.keyCode != 16) {
2829			$('#memberID').val('');
2830		}
2831	});
2832    $('html body').on('change', '#memberID, #member-name', function(){
2833	//when this is empty we don't need the division
2834	var memberid = $('#memberID').val();
2835	if(memberid == '') {
2836	    $('#divColumn').show();
2837	}else {
2838	    // $('#divColumn').hide();
2839	    //we also need to check if this number is valid
2840	    $.get('/wp-admin/admin-ajax.php?action=is_mh_valid&id='+memberid+'&dbaction=member', function(data){
2841		if(data.invalid){
2842			$('#memberID').val('').focus();
2843			$('#member-name').val('');
2844			$('.error-msg').text('That number is invalid!').show();
2845			setTimeout(function(){
2846				$('.error-msg').hide();
2847			}, 6000);
2848		}
2849	    });
2850	}
2851    });
2852	$('html body').on('keydown', '#horseID', function(event){
2853		//don't do anything if the tab is pressed
2854		if(event.keyCode != 9 && event.keyCode != 16) {
2855			$('#horse_name').val('');
2856		}
2857	});
2858	$('html body').on('keydown', '#horse_name', function(event){
2859		//don't do anything if the tab is pressed
2860		if(event.keyCode != 9 && event.keyCode != 16) {
2861			$('#horseID').val('');
2862		}
2863	});
2864    $('html body').on('change', '#horseID, #horse_name', function(){
2865		//when this is empty we don't need the division
2866		var horseid = $('#horseID').val();
2867		if(horseid != '') {
2868		    //we also need to check if this number is valid
2869		    $.get('/wp-admin/admin-ajax.php?action=is_mh_valid&id='+horseid+'&dbaction=horse', function(data){
2870			if(data.invalid){
2871			    $('#horseID').val('').focus();
2872			    $('#horse_name').val('');
2873			    $('.error-msg').text('That number is invalid!').show();
2874			    setTimeout(function(){
2875				$('.error-msg').hide();
2876			    }, 6000);
2877			}
2878		    });
2879		}
2880	    });
2881    $('html body').on('blur', '#ride_results_form #memberID', function(){
2882	setTimeout(function(){
2883	    if($('#memberID').val() == '') {
2884		if($('#member-name').val() == '') {
2885		    
2886		} else {
2887		    $('.non-member').show();
2888		}
2889	    }else {
2890		$('.non-member').hide();
2891	    }
2892	},1000);
2893    });
2894    $('html body').on('blur', '#ride_results_form #member-name', function(){
2895	setTimeout(function(){
2896	    if($('#memberID').val() == '') {
2897		if($('#member-name').val() == '') {
2898		    
2899		} else {
2900		    $('.non-member').show();
2901		}
2902	    }else {
2903		$('.non-member').hide();
2904	    }
2905	},1000);
2906    });
2907
2908    $('html body').on('change', '.bc_update', function(){
2909		var thisname = $(this).attr('name');
2910	
2911		var par = $(this).closest('.bc_input_row');
2912	
2913	    var rider = $(par).find('.rider_number').val();
2914	    if(rider == '') {
2915			return false;
2916	    }
2917	    //add a new line when the rider number is entered
2918	    if(thisname == 'rider_number'){
2919			//show the next row
2920			$(par).next().show();
2921	    }
2922	    var item = $(this).attr('name');
2923	    var itemval = $(this).val();
2924	    var distance = $(this).data('distance');
2925
2926		var submit_flag = 1;
2927		if ($(this).hasClass("rider_weight")) {
2928			if($(this).val() <= 0) {
2929				submit_flag = 0;
2930				$("#rider_weight_sero_warning_message").css("display", "block");
2931			} else {
2932				$("#rider_weight_sero_warning_message").css("display", "none");
2933			}
2934		}
2935
2936		if(submit_flag == 1) {
2937			
2938			$(par).find('.rider_number').prop('readonly', true);
2939			$.post('/wp-admin/admin-ajax.php?action=aerc_post_bc_calc', {rider: rider, item: item, itemval: itemval, distance: distance}, function(data){
2940				if(data.filled == 7) {
2941					//show the next row
2942				}
2943				if(data.html) {
2944					//show the results
2945					$('.bc_entry_results').html(data.html);
2946				}
2947			});
2948		}
2949    });
2950
2951    $('html body').on('click', '.remove-bc-row', function(e){
2952		e.preventDefault();
2953		var distanceID = $(this).data('distance');
2954		var rider_number = $(this).closest('.bc_input_row').find('.rider_number').prop('readonly', false).val();
2955		$.post('/wp-admin/admin-ajax.php?action=remove_bc_row', {distance: distanceID, rider: rider_number}, function(data){
2956			$('.bc_entry_results').html(data.html);
2957		});
2958		$(this).closest('.bc_input_row').find('.bc_update').val('');
2959	});
2960
2961    $('html body').on('keydown', '.ridetime, .finishtime', function(){
2962		// $('.ridetime').unmask();
2963		// $('.ridetime').mask("00:00:00");
2964		// $('.finishtime').unmask();
2965		// $('.finishtime').mask("00:00:00 AA");
2966    });
2967
2968    $('html body').on('click', '.edit-ride-result', function(e){
2969	e.preventDefault();
2970	var id = $(this).data('id');
2971	var rideorfinish = $('#calc_type').val();
2972	$.get('/wp-admin/admin-ajax.php?action=aerc_edit_ride_results&result='+id+'&calc='+rideorfinish, function(data){
2973	    $('#rm_rider_id').val(data.rm_rider_id);
2974	    $('#rm_rider_id').attr('data-oldid', data.rm_rider_id);
2975	    $('#rm_rider_id').data('oldid', data.rm_rider_id);
2976	    $('#memberID').val(data.member_id);
2977	    $('#member-name').val(data.rider_name);
2978	    $('#division').val(data.division_id);
2979	    $('#horseID').val(data.horse_id);
2980	    $('#horse_name').val(data.horse_name);
2981	    $('#ownerID').val(data.owner_id);
2982	    $('#horse-owner-name').val(data.member_owner_name);
2983	    $('#finish-time').val(data.finish_time);
2984	    $('#finish_code').val(data.finish_code);
2985	    var riderdets = $.parseJSON(data.rider_details);
2986	    $('#address').val(data.address);
2987	    $('#phone').val(data.phone);
2988	    $('#email').val(data.email);
2989	    if(data.member_id == null) {
2990		$('.non-member').show();
2991	    }else{
2992		$('.non-member').hide();
2993	    }
2994	    if(rideorfinish == 'ft') {
2995		$('#finishorride').text('Finish Time');
2996	    }else{
2997		$('#finishorride').text('Ride Time');
2998	    }
2999	    $([document.documentElement, document.body]).animate({
3000	        scrollTop: $("#ride-results-entry").offset().top
3001	    }, 700);
3002	});
3003    });
3004    $('html body').on('mouseenter', 'input.disabled[type="submit"]',function(){
3005	$('.errors-present').addClass('highlight');
3006	var link = $('.aerc-errors-mgs').first()
3007	var el = $(link).offset().top;
3008	var dist = el - 350;
3009	setTimeout(function(){
3010	    $('.errors-present').removeClass('highlight');
3011	    $(link).find('.correct-rr-error').trigger('click');
3012	    $([document.documentElement, document.body]).animate({
3013	        scrollTop: dist
3014	    }, 700);
3015	}, 750);
3016    });
3017    $('html body').on('submit', '#ride_results_form', function(e){
3018		//    $('#ride_results_form').submit(function(e){
3019    	e.preventDefault();
3020    	//is the ride time valid?
3021    	var form = $(this).serialize();
3022    	var distance = $(this).find('#distance').find('option:selected').data('distanceid');
3023    	var submit = $(this).find('input[name="finalize"]');
3024    	$(submit).closest('.form-column').append('<i class="fa fa-circle-o-notch fa-spin result-loading"></i>')
3025
3026    	$.post('/wp-admin/admin-ajax.php?action=ride_results', form, function(data){
3027			bc_update_row()
3028    	});
3029		$('#rm_rider_id').focus();
3030    });
3031
3032	// add an option to update the entire row instead of one field at a time
3033	function bc_update_row() {
3034		var item = '',
3035			item_val = '',
3036			bc_row = '',
3037			bc_obj = {},
3038			count = $('.bc_input_row').length;
3039		//post each row
3040		
3041		$('.bc_input_row').each(function(i){
3042			bc_row = $(this);
3043			bc_obj = {update_by_row: 'update_by_row'};
3044			$(this).find('.bc_update').each(function(){
3045				item = $(this).attr('name');
3046				bc_obj[item] = $(this).val();
3047				bc_obj.distance = $(this).data('distance');
3048			});
3049			
3050			if(Object.keys(bc_obj).length == 9 && bc_obj.rider_number)
3051			{
3052				$(bc_row).find('.rider_number').prop('readonly', true);
3053				$.post('/wp-admin/admin-ajax.php?action=aerc_post_bc_calc', bc_obj, function(data){
3054					$()
3055					if(data.html) {
3056						//show the results
3057						$('.bc_entry_results').html(data.html);
3058					}
3059				});
3060			}
3061			if(i+1 === count) {
3062				after_bc_calculate();
3063			}
3064		});
3065	}
3066
3067	var bc_elements_number = 0;
3068	function bc_update_trigger() {
3069		var bc_elements = document.getElementsByClassName("bc_update");
3070		bc_elements_number = bc_elements.length;
3071		var bc_interval = setInterval(function () {
3072			bc_elements_number = bc_elements_number - 1;
3073			if(bc_elements[bc_elements_number] != undefined || bc_elements[bc_elements_number] != null) {
3074				bc_calculate(bc_elements[bc_elements_number]);
3075			}
3076			if(bc_elements_number == 1) {
3077				after_bc_calculate();
3078				clearInterval(bc_interval);
3079			}
3080		}, 15);
3081	}
3082
3083	function bc_calculate(element) {
3084		//post data
3085		var thisname = $(element).attr('name');
3086	
3087		var par = $(element).closest('.bc_input_row');
3088	
3089		
3090		var rider = $(par).find('.rider_number').val();
3091		if(rider == '') {
3092			return false;
3093		}
3094		//add a new line when the rider number is entered
3095		if(thisname == 'rider_number'){
3096			//show the next row
3097			$(par).next().show();
3098		}
3099		var item = $(element).attr('name');
3100		var itemval = $(element).val();
3101		var distance = $(element).data('distance');
3102		
3103		var submit_flag = 1;
3104		if ($(element).hasClass("rider_weight")) {
3105			if($(element).val() <= 0) {
3106				submit_flag = 0;
3107				$("#rider_weight_sero_warning_message").css("display", "block");
3108			} else {
3109				$("#rider_weight_sero_warning_message").css("display", "none");
3110			}
3111		}
3112
3113		if(submit_flag == 1) {
3114			
3115			$(par).find('.rider_number').prop('readonly', true);
3116			$.post('/wp-admin/admin-ajax.php?action=aerc_post_bc_calc', {rider: rider, item: item, itemval: itemval, distance: distance}, function(data){
3117				if(data.filled == 7) {
3118					//show the next row
3119				}
3120				if(data.html) {
3121					//show the results
3122					$('.bc_entry_results').html(data.html);
3123				}
3124			});
3125		}
3126	}
3127
3128	function after_bc_calculate() {
3129		var submit = $("#ride_results_form").find('input[name="finalize"]');
3130		var distance = $("#ride_results_form").find('#distance').find('option:selected').data('distanceid');
3131		$(submit).closest('.form-column').remove('.result-loading');
3132
3133		var type = $('#calc_type').val();
3134		$('#ride-results-details').html('<div style="text-align: center; font-size: 36px;"><i class="fa fa-circle-o-notch fa-spin result-loading"></i></div>');
3135		$.get('/wp-admin/admin-ajax.php?action=ride_results_details&distance='+distance+'&type='+type, function(data){
3136			$('#ride-results-details').html(data.html);
3137			$('.ride-results-page-details').show(); 
3138			$('.result-loading').remove();
3139				$('#ride_results_table').DataTable({
3140				responsive: {
3141					details: {
3142						type: 'column'
3143					}
3144				},
3145				columnDefs: [ {
3146					className: 'control',
3147					orderable: false,
3148					targets:   0
3149				} ],
3150			dom: 'Bfrtip',
3151				buttons: [
3152					'print'
3153				]
3154			} );
3155		});
3156		setTimeout(function(){
3157			$('#form-message').hide();				
3158		}, 2500);
3159			//    		$('.reset').val('');
3160		$('#rr-ind-results-wrapper').load('/membership/ride-results #rr-ind-results', function(){
3161			setTimeout(function(){
3162				$('#rm_rider_id').focus();
3163			},100);
3164		});
3165			//    	        $('.ridetime').unmask();
3166			//	        $('.ridetime').mask("00:00:00");
3167			//	        $('.finishtime').unmask();
3168			//	        $('.finishtime').mask("00:00:00 AA");
3169		//$('#division')[0].sumo.reload();
3170		$('#pay-status').text('');
3171
3172
3173		setTimeout(function(){
3174			var type = $("#calc_type").val();
3175			if(type == 'ft') {
3176				$('#finish-time').removeClass('ridetime');
3177				$('#finish-time').addClass('finishtime');
3178				$('.ft-show').show();
3179				$("#calc_type").closest('.aerc-grid').addClass('one-one-one-one-two').removeClass(' one-
3179one-one-three');
3180				$('#finishorride').text('Finish Time');
3181			}				
3182		}, 2500);
3183	}
3184
3185    $(document).on('keydown', '#finish-time', function(e) {
3186        //your code
3187        if (e.keyCode != 8 && (this.value.length === 2 || this.value.length === 5)) {
3188            this.value += ":";
3189        }
3190        //collapse double colons
3191        if (this.value.endsWith("::")) {
3192            this.value = this.value.replace(/:+/g, ":");
3193        }
3194    });
3195/*
3196	$(document).on('blur', '#finish-time', function(){
3197		if(this.value.endsWith(":")) {
3198			this.value = this.value.slice(0, -1) + '';
3199		}
3200		
3201		//does this value have a colon at the end?
3202		if(holdtime.endsWith(':'))
3203		{
3204			holdtime = holdtime.slice(0, -1);
3205			$(this).val(holdtime);
3206		}
3207	});
3208*/
3209    $('html body').on('change', '#rm_rider_id', function(){
3210    	var $this = $(this);
3211    	var rmid = $(this).val();
3212    	var rmoldid = $(this).data('oldid');
3213    	var distanceid = $('#distance').val();
3214        if(rmid != rmoldid) {
3215			console.log('/wp-admin/admin-ajax.php?action=ride_manager_number_check&distance='+distanceid+'&rmid='+rmid);
3216        	$.get('/wp-admin/admin-ajax.php?action=ride_manager_number_check&distance='+distanceid+'&rmid='+rmid, function(data){
3217				console.log(data);
3218        	    $('.error-msg').hide();
3219        		if(data.dup){
3220        			$(this).val('').focus();
3221        			$('.error-msg').text('That number is in use!').show();
3222        			setTimeout(function(){
3223        				$('.error-msg').hide();
3224        			}, 6000);
3225        		}else{
3226    
3227        		}
3228        	});	   
3229        }else{
3230        	$('.error-msg').hide();
3231        }
3232    });
3233    $('#hold-time').change(function(){
3234    	var lastVal = $('#distance').find('option:selected').data('holdtime');
3235    	var distanceid = $('#distance').val();
3236		var type = $('#calc_type').val();
3237		var holdtime = $(this).val();
3238		//does this value have a colon at the end?
3239		if(holdtime.endsWith(':'))
3240		{
3241			holdtime = holdtime.slice(0, -1);
3242			$(this).val(holdtime);
3243		}
3244    	if(lastVal.length) {
3245    		if(confirm('Are you sure?  This will update any ride results for this distance.')) {
3246    			updateHoldTime(holdtime, distanceid);
3247    		}
3248    	}else{
3249    		updateHoldTime(holdtime, distanceid);
3250    	}
3251		$('#ride-results-details').html('<div style="text-align: center; font-size: 36px;"><i class="fa fa-circle-o-notch fa-spin result-loading"></i></div>');
3252		$.get('/wp-admin/admin-ajax.php?action=ride_results_details&distance='+distanceid+'&type='+type, function(data){
3253		    $('#ride-results-details').html(data.html);
3254		    $('.ride-results-page-details').show(); 
3255		    $('#ride_results_table').DataTable({
3256		        responsive: {
3257		            details: {
3258		                type: 'column'
3259		            }
3260		        },
3261		        columnDefs: [ {
3262		            className: 'control',
3263		            orderable: false,
3264		            targets:   0
3265		        } ],
3266		        dom: 'Bfrtip',
3267		        buttons: [
3268		            'print'
3269		        ]
3270		    } );
3271		});	
3272    });
3273    function updateHoldTime(time, distance) {
3274		$('#offline-distance').find('option:selected').data('holdtime', time);
3275
3276		$('#distance option:selected').data('holdtime', time);
3277		$('#ride_results_form #distance').find('option:selected').attr('data-holdtime', time);
3278    	$.post('/wp-admin/admin-ajax.php?action=aerc_update_hold_time', {time: time, distance: distance}, function(){
3279    		
3280    	});
3281    	return true;
3282    }
3283    $('#start-time').change(function(){
3284    	if(confirm('Are you sure?  This will update any ride results for this distance.')){
3285    		var time = $(this).val(),
3286    		    distanceid = $('#distance').val();
3287
3288    		var type = $('#calc_type').val();
3289
3290			//does this value have a colon at the end?
3291			if(time.endsWith(':'))
3292			{
3293				time = time.slice(0, -1);
3294				$(this).val(time);
3295			}
3296
3297    		$.post('/wp-admin/admin-ajax.php?action=aerc_update_start_time', {time: time, distance: distanceid}, function(){
3298				$('#ride-results-details').html('<div style="text-align: center; font-size: 36px;"><i class="fa fa-circle-o-notch fa-spin result-loading"></i></div>');
3299    			$.get('/wp-admin/admin-ajax.php?action=ride_results_details&distance='+distanceid+'&type='+type, function(data){
3300    			    $('#ride-results-details').html(data.html);
3301    			    $('.ride-results-page-details').show(); 
3302
3303					$('#distance option:selected').data('time', time);
3304					$('#ride_results_form #distance').find('option:selected').attr('data-time', time);
3305    			    $('#ride_results_table').DataTable({
3306    			        responsive: {
3307    			            details: {
3308    			                type: 'column'
3309    			            }
3310    			        },
3311    			        columnDefs: [ {
3312    			            className: 'control',
3313    			            orderable: false,
3314    			            targets:   0
3315    			        } ],
3316    			        dom: 'Bfrtip',
3317    			        buttons: [
3318    			            'print'
3319    			        ]
3320    			    } );
3321    			});	 
3322    		});
3323    	}
3324    });
3325    $('.ride-results-page-details').on('click', '.finalize_ride.rr-error', function(e){
3326	e.preventDefault();
3327    });
3328	$('html body').on('click', '#call-intro-modal', function(e){
3329		e.preventDefault();
3330		var modal = '#mdl_intro_riders';
3331		$(modal).removeClass('desactive-modal').addClass('active-modal');
3332		$cuerpo.addClass('fixed');
3333	});
3334    $('.ride-results-page-details').on('click', '.finalize_ride.can-send#finalizeRideResults', function(e){
3335	    var modal = '#rrPaymentForm';
3336	    $(modal).removeClass('desactive-modal').addClass('active-modal');
3337	    $cuerpo.addClass('fixed'); 
3338	});
3339	/* disabled
3340    $('.ride-results-page-details').on('click', '.finalize_ride.can-send', function(e){
3341	e.preventDefault();
3342	var btn = $(this);
3343	$(btn).text('Updating...');
3344	//finalize this ride
3345	var rideid = $(this).data('id');
3346	var type = $('#calc_type').val();
3347	$.post('/wp-admin/admin-ajax.php?action=manager_finalize_ride',{id: rideid}, function(data){
3348		$('#ride-results-details').html('<div style="text-align: center; font-size: 36px;"><i class="fa fa-circle-o-notch fa-spin result-loading"></i></div>');
3349		$.get('/wp-admin/admin-ajax.php?action=ride_results_details&distance='+rideid, function(data){
3350		    $('#ride-results-details').html(data.html);
3351		    $('.ride-results-page-details').show(); 
3352		    $('#ride_results_table').DataTable({
3353		        responsive: {
3354		            details: {
3355		                type: 'column'
3356		            }
3357		        },
3358		        columnDefs: [ {
3359		            className: 'control',
3360		            orderable: false,
3361		            targets:   0
3362		        } ],
3363		        dom: 'Bfrtip',
3364		        buttons: [
3365		            'print'
3366		        ]
3367		    } );
3368		});	
3369		// $(btn).text('Finalized');
3370	});
3371    });
3372	*/
3373    $('.ride-results-page-details').on('click', '.remove-ride-result', function(e){
3374	e.preventDefault();
3375	var id = $(this).data('id');
3376	var distance = $(this).data('distance');
3377	var rmid = $(this).data('rmid');
3378	var type = $('#calc_type').val();
3379//	if(confirm('Are you sure you want to delete?'){
3380        	$.post('/wp-admin/admin-ajax.php?action=remove_ride_result', {id: id}, function(data){
3381        	        var el = $('.bc_update.rider_number[value="'+rmid+'"]');
3382        	        var row = $(el).closest('.bc_input_row');
3383        	        var remove = $(row).find('.remove-bc-row');
3384        	        $(remove).trigger('click');
3385				$('#ride-results-details').html('<div style="text-align: center; font-size: 36px;"><i class="fa fa-circle-o-notch fa-spin result-loading"></i></div>');
3386        		$.get('/wp-admin/admin-ajax.php?action=ride_results_details&distance='+distance+'&type='+type, function(data){
3387        			$('#ride-results-details').html(data.html);
3388        			$('.ride-results-page-details').show(); 
3389        			    $('#ride_results_table').DataTable({
3390        			        responsive: {
3391        			            details: {
3392        			                type: 'column'
3393        			            }
3394        			        },
3395        			        columnDefs: [ {
3396        			            className: 'control',
3397        			            orderable: false,
3398        			            targets:   0
3399        			        } ],        
3400        			        dom: 'Bfrtip',
3401        			        buttons: [
3402        			            'print'
3403        			        ]
3404        			    } );
3405        		});	    
3406        	});	    
3407//	});
3408
3409    });
3410    $('html body').on('click', '.remove-all-results', function(e){
3411		e.preventDefault();
3412		let distanceID = $('.remove-ride-result:first').data('distance'),
3413		    type = $('#calc_type').val();
3414
3415		$.post('/wp-admin/admin-ajax.php?action=remove_ride_result', {distance: distanceID}, function(){
3416			$('.remove-bc-row').trigger('click');
3417			$('.update_starters_finishers').val('0').trigger('blur');
3418    		$.get('/wp-admin/admin-ajax.php?action=ride_results_details&distance='+distanceID+'&type='+type, function(data){
3419    			$('#ride-results-details').html(data.html);
3420    			$('.ride-results-page-details').show(); 
3421    			    $('#ride_results_table').DataTable({
3422    			        responsive: {
3423    			            details: {
3424    			                type: 'column'
3425    			            }
3426    			        },
3427    			        columnDefs: [ {
3428    			            className: 'control',
3429    			            orderable: false,
3430    			            targets:   0
3431    			        } ],        
3432    			        dom: 'Bfrtip',
3433    			        buttons: [
3434    			            'print'
3435    			        ]
3436    			    } );
3437    		});	
3438		});
3439    });
3440    $('#aerc_rider_history_form').submit(function(e){
3441	e.preventDefault();
3442	var form = $(this).serialize();
3443	$('.dirctory-results .cnt').html('<h1 style="text-align: center;"><i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i><br />Click only once - hold your horses!</h1>');
3444	$.post('/wp-admin/admin-ajax.php?action=aerc_rider_history', form, function(data){
3445			if(data.html) {
3446				$('.dirctory-results .cnt').html(data.html);
3447			}
3448		});
3449    });
3450    $('html body').on('click', '.get_rider_history, .get_rider_history_selected', function(e){
3451    	e.preventDefault();
3452    	var thislink = $(this).clone();
3453    	var thistext = thislink.text();
3454
3455    	var backlink = JSON.parse(sessionStorage.getItem("links"));
3456
3457		backlink.push(thistext);
3458		sessionStorage.setItem("links", JSON.stringify(backlink));
3459		thislink.prepend(' Return to ').appendTo('.modal-breadcrumbs');
3460
3461    	var id = $(this).data('id');
3462    	var noid = $(this).data('noid');
3463    	$('#rideRideResults').html('<center><i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i><br />Click only once - hold your horses!</center>');
3464
3465    	var modal = '#rideResults';
3466		$(modal).removeClass('desactive-modal').addClass('active-modal');
3467		$cuerpo.addClass('fixed');
3468    	$.post('/wp-admin/admin-ajax.php?action=aerc_rider_history', {member_id: id, noid: noid}, function(data){
3469        	$('#rideRideResults').html(data.html);  		
3470    	});
3471    });
3472    if($('.get_rider_history_selected').length){
3473    	$('.get_rider_history_selected').trigger('click');
3474    }
3475    if($('.get_horse_history_selected').length){
3476    	$('.get_horse_history_selected').trigger('click');
3477    }
3478    	
3479    $('#aerc_equine_history_form').submit(function(e){
3480	e.preventDefault();
3481	var form = $(this).serialize();
3482	$('.dirctory-results .cnt').html('<h1 style="text-align: center;"><i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i><br />Click only once - hold your horses!</h1>');
3483	$.post('/wp-admin/admin-ajax.php?action=aerc_horse_history', form, function(data){
3484	    if(data.html) {
3485		$('.dirctory-results .cnt').html(data.html);
3486	    }
3487	});
3488    });
3489    $('html body').on('click', '.get_horse_history, .get_horse_history_selected', function(e){
3490	e.preventDefault();
3491	var thislink = $(this).clone();
3492	var thistext = thislink.text();
3493
3494	var backlink = JSON.parse(sessionStorage.getItem("links"));
3495
3496	backlink.push(thistext);
3497	sessionStorage.setItem("links", JSON.stringify(backlink));
3498	thislink.prepend(' Return to ').appendTo('.modal-breadcrumbs');
3499
3500
3501	var id = $(this).data('id');
3502	var noid = $(this).data('noid');
3503	
3504    var modal = '#rideResults';
3505    $(modal).removeClass('desactive-modal').addClass('active-modal');
3506    $cuerpo.addClass('fixed');
3507
3508	$('#rideRideResults').html('<center><i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i></center><br />Click only once - hold your horses!');
3509	
3510	$.post('/wp-admin/admin-ajax.php?action=aerc_horse_history', {member_id: id, noid: noid}, function(data){
3511	    $('#rideRideResults').html(data.html);  		
3512	});
3513    });
3514    $('#uploader').fineUploader({
3515      request: {
3516        endpoint: '/wp-content/themes/aerc/js/uploader/uploader/upload.php',
3517      },
3518      multiple: false,
3519      validation: {
3520        allowedExtensions: ['xls', 'xlsx','txt'],
3521        sizeLimit: 31457280 // 75 kB = 30 * 1024 * 1024 bytes
3522      },
3523      text: {
3524        uploadButton: 'Click to Upload Completed ERIC File or XLSX Template'
3525       }
3526    }).on('complete', function(event, id, fileName, responseJSON) {
3527      if (responseJSON.success) {
3528	  var calc = $('#calc_type').val();
3529	  var time = $('#start-time').val();
3530	  var holdtime = $('#hold-time').val();
3531	  var date = $('#distance').find('option:selected').data('date');
3532	  var distance = $('#distance').find('option:selected').data('distance');
3533	  var distanceID = $('#distance').find('option:selected').data('distanceid');
3534        $.ajax({
3535          type: "GET",
3536          url: "/wp-admin/admin-ajax.php?action=xls_parser",
3537          data: {File: responseJSON.uploadName, startTime: time, startDate: date, distance: distance, calcType: calc, holdtime: holdtime, distanceID: distanceID},
3538          success: function(data){
3539			$('.qq-upload-list li').remove();
3540            $('#rr-ind-results').html(data.rs);
3541			$('.bc_input_row.first-row').closest('.bc_calc_form').html(data.bc);
3542			if(data.starters){
3543				$('#starters').val(data.starters);
3544				$('#ride_results_form #distance option:selected').data('starters', data.starters);
3545				$('#ride_results_form #distance').find('option:selected').attr('data-starters', data.starters);
3546			}
3547			if(data.finishers){
3548				$('#finishers').val(data.finishers);
3549				$('#ride_results_form #distance option:selected').data('finishers', data.finishers);
3550				$('#ride_results_form #distance').find('option:selected').attr('data-finishers', data.finishers);
3551			}
3552			if(data.juniors){
3553				$('#juniors').val(data.juniors);
3554				$('#ride_results_form #distance option:selected').data('juniors', data.juniors);
3555				$('#ride_results_form #distance').find('option:selected').attr('data-juniors', data.juniors);
3556			}
3557            if($('.errors-present').length) {
3558            	$('input[name="finalize"]').attr('disabled', true).addClass('disabled');
3559            };
3560			
3561          }
3562        });
3563      }
3564    });
3565
3566    $('html body').on('click', '.aerc-rr-block .disabled, .correct-rr-error', function(e){
3567    	e.preventDefault();
3568    	$(this).closest('.aerc-rr-block').find('input').removeClass('disabled').prop('disabled', false);
3569    	$(this).closest('.aerc-rr-block').find('select').removeClass('disabled').prop('disabled', false);
3570    	$(this).closest('.aerc-rr-block').find('.aerc-errors-list').remove();
3571    	$(this).closest('.aerc-errors-mgs').remove();
3572    	if(!$('.correct-rr-error').length) {
3573        	$('input[name="finalize"]').removeAttr('disabled').removeClass('disabled');
3574        	$('.errors-present').remove();
3575    	}
3576    });
3577	$('html body').on('click', '.remove-entry', function(e){
3578	    e.preventDefault();
3579	    $(this).closest('.aerc-rr-block').remove();
3580	    	if(!$('.correct-rr-error').length) {
3581	        	$('input[name="finalize"]').removeAttr('disabled').removeClass('disabled');
3582	        	$('.errors-present').remove();
3583	    	}
3584	});
3585    $('html body').on('click', '#calendarDiv td span.details', function(){
3586	
3587    	$(this).closest('div').find('.toggle-ride-dets').toggle('10', function() {
3588    	    if ($(this).is(':visible')) {
3589    			$(this).css('display','table-row');
3590    	    }
3591    	});
3592
3593    });
3594    $('html body').on('click', '.switch-user-select', function(e){
3595	e.preventDefault();
3596	var member = $(this).data('member');
3597	Cookies.set('aerc_superuser_member', member);
3598	location.reload();
3599    });
3600    $('html body').on('click', '.clear-switch-user', function(e){
3601	e.preventDefault();
3602	Cookies.remove('aerc_superuser_member');
3603	$('.su-clear-message').text('Member Cleared!');
3604    });
3605    $('.btn-toggle').click(function(e){
3606	e.preventDefault();
3607	var val = $(this).data('value');
3608	var toggle = $(this).data('toggle');
3609	if(val == 'yes') {
3610	    $(toggle).show();
3611		$(toggle).find('input, select, textarea').attr('required', false).removeAttr('data-val data-val-required');
3612		$(toggle).find('[data-required]').each(function(){
3613			$(this).attr('required', true).attr('data-val', 'true').attr('data-val-required', 'This field is required');
3614		});
3615	} else {
3616		if(val == 'no') {
3617			$(toggle).hide();
3618			$(toggle).find('input, select, textarea').attr('required', false).removeAttr('data-val data-val-required');
3619			// Hidden inputs still serialize on submit, so clear their values
3620			// to prevent ghost family/horse rows from reaching the server.
3621			$(toggle).find('input[type="text"], input[type="email"], input[type="tel"], input[type="number"], input[type="date"], textarea').val('');
3622			$(toggle).find('select').prop('selectedIndex', 0).trigger('change');
3623			$(toggle).find('input[type="checkbox"], input[type="radio"]').prop('checked', false);
3624		}
3625	}
3626	$(this).closest('.toggle-group').find('.btn-toggle').removeClass('active');
3627	$(this).addClass('active');
3628
3629
3630    });
3631	$(document).ready(function() {
3632		if($('.recalulate-on-load').length > 0) {
3633			$('.recalulate-on-load').trigger('change');
3634		}
3635	});
3636    if($('.enroll-type').length) {
3637	var specials = $('.enroll-type').data('specials');
3638	if(specials == 0) {
3639	    $('.ps0').trigger('change').trigger('click');
3640	    $('.enroll-type').hide();
3641	    $('.hidden-till-fee-selected').slideDown();
3642	}
3643    }
3644
3645
3646	// Helpers for cleaning line-item labels coming from form labels / slugs.
3647	// Stops cosmetic noise like "Membership Type *" or raw "fee_2" leaking
3648	// onto receipts. Used by both .recalculate and .join-form-recalcuate.
3649	function aercCleanLineLabel(text){
3650		if(!text) return '';
3651		return String(text)
3652			.replace(/[ \s]+/g, ' ')
3653			.replace(/\s*\(\s*required\s*\)\s*/ig, '')
3654			.replace(/^\s*\*+\s*/, '')
3655			.replace(/\s*\*+\s*$/, '')
3656			.trim();
3657	}
3658	function aercHumanizeSlug(slug){
3659		if(!slug) return '';
3660		return String(slug)
3661			.replace(/[\[\]'"]/g, ' ')
3662			.replace(/[_\-]+/g, ' ')
3663			.replace(/([a-z])([A-Z])/g, '$1 $2')
3664			.replace(/\s+/g, ' ')
3665			.trim()
3666			.replace(/\b\w/g, function(c){ return c.toUpperCase(); });
3667	}
3668
3669	$('.recalculate').trigger('change');
3670	$('.join-form-recalcuate').trigger('change');
3671
3672    $('html body').on('change', '.recalculate', function(){
3673        var $form = $(this).closest('form');
3674        var fees = [];
3675        var donations = [];
3676        var familyInternational = 0;
3677        var maxInternational = parseInt($('.ps0').data('internationalfamily')) || 0;
3678        var fee = 0;
3679        var lineItems = [];
3680
3681        function addLine(id,label,amount){
3682            amount = parseFloat(amount);
3683            if(isNaN(amount) || amount <= 0) return;
3684            var cleanId = (id||('FEE'+(lineItems.length+1))).toString().replace(/[^A-Za-z0-9]/g,'').substring(0,31);
3685            var existing = lineItems.find(i=>i.id === cleanId);
3686            if(existing){
3687                // merge duplicate ids
3688                existing.unitPrice = (parseFloat(existing.unitPrice) + amount).toFixed(2);
3689            } else {
3690                // Humanize the id when no label was supplied so the receipt
3691                // reads "Fee 2" instead of leaking "fee_2" or "FEE2".
3692                var displayName = label || aercHumanizeSlug(id || cleanId) || 'Fee';
3693                lineItems.push({
3694                    id: cleanId,
3695                    name: displayName.toString().substring(0,31),
3696                    description: displayName.toString().substring(0,255),
3697                    quantity: 1,
3698                    unitPrice: amount.toFixed(2),
3699                    taxable: false
3700                });
3701            }
3702        }
3703
3704        $('.recalculate').not('.zero-on-recalculate').each(function(){
3705            var $el = $(this);
3706            var rawName = $el.attr('name') || '';
3707            var labelText = $el.closest('.form-column').find('label[for="'+$el.attr('id')+'"]').text();
3708            var lineLabel = $el.data('line-name')
3709                || aercCleanLineLabel(labelText)
3710                || aercHumanizeSlug(rawName)
3711                || rawName;
3712
3713            if($el.attr('name') == 'family_member_mbr_division[]'){
3714                $el.closest('.edit-group').find('.zero-on-recalculate').attr('data-calcvalue', '0');
3715            }
3716
3717            var tagName = $el.prop('tagName').toLowerCase();
3718            var thisFee = 0;
3719
3720            if(!$el.hasClass('donations')) {
3721                if(tagName === 'select') {
3722                    if($el.find('option:selected').attr('data-calcvalue')) {
3723                        thisFee = parseFloat($el.find('option:selected').attr('data-calcvalue'));
3724                    } else {
3725                        thisFee = parseFloat($el.find('option:selected').attr('value'));
3726                    }
3727                } else {
3728                    if($el.attr('data-calcvalue')) {
3729                        thisFee = parseFloat($el.attr('data-calcvalue'));
3730                    } else {
3731                        thisFee = parseFloat($el.val());
3732                    }
3733                }
3734            } else {
3735                // donation path
3736                if($el.attr('data-calcvalue')) {
3737                    thisFee = parseFloat($el.attr('data-calcvalue'));
3738                } else {
3739                    thisFee = parseFloat($el.val());
3740                }
3741            }
3742
3743            if(isNaN(thisFee)) thisFee = 0;
3744
3745            // Additional horse logic: first horse free (original logic preserved)
3746            if($el.hasClass('additionalHorseFeeVal')) {
3747                thisFee = 0;
3748                if($el.attr('data-calcvalue')) {
3749                    thisFee = parseFloat($el.attr('data-calcvalue'));
3750                } else {
3751                    thisFee = parseFloat($el.val());
3752                }
3753                if(!$el.closest('.equine-clone').hasClass('cloned-group')) {
3754                    thisFee = 0;
3755                }
3756                if($el.closest('.family-clone').length) {
3757                    if($el.closest('.family-clone').find('.family-equine-clone').length == 1) {
3758                        thisFee = 0;
3759                    }
3760                }
3761            }
3762
3763            // International family cap
3764            if($el.hasClass('aercInternational')) {
3765                var intlVal = 0;
3766                if($el.attr('data-calcvalue')) {
3767                    intlVal = parseFloat($el.attr('data-calcvalue')) || 0;
3768                } else if ($el.find('option:selected').attr('data-calcvalue')) {
3769                    intlVal = parseFloat($el.find('option:selected').attr('data-calcvalue')) || 0;
3770                } else {
3771                    intlVal = parseFloat($el.val()) || 0;
3772                }
3773                if(familyInternational < maxInternational) {
3774                    var projected = familyInternational + intlVal;
3775                    if(projected <= maxInternational) {
3776                        familyInternational = projected;
3777                        thisFee = intlVal;
3778                    } else {
3779                        // only allow remainder up to cap (or zero if already reached)
3780                        thisFee = 0;
3781                        familyInternational = maxInternational;
3782                    }
3783                } else {
3784                    thisFee = 0;
3785                }
3786            }
3787
3788            // Skip invalid / excluded ids
3789            if($el.attr('id') == 'clone_family_renew' || isNaN(thisFee)) {
3790                thisFee = 0;
3791            }
3792
3793            if($el.hasClass('donations')) {
3794                if(thisFee > 0) {
3795                    donations.push(thisFee);
3796                    addLine(rawName || 'donation', lineLabel, thisFee);
3797                }
3798                //return;
3799            }
3800
3801            if(thisFee > 0){
3802                fees.push(thisFee);
3803                addLine(rawName || ('fee_'+fees.length), lineLabel, thisFee);
3804            }
3805        });
3806
3807        // Donations already handled above in-loop where class donations present
3808        $('.donations').each(function(){
3809            var dVal = 0;
3810            if($(this).attr('data-calcvalue')) {
3811                dVal = parseFloat($(this).attr('data-calcvalue'));
3812            } else {
3813                dVal = parseFloat($(this).val());
3814            }
3815            if(isNaN(dVal)) dVal = 0;
3816            if(dVal > 0 && !lineItems.find(li =>
3816 li.id === ($(this).attr('name')||'donation').replace(/[^A-Za-z0-9]/g,''))) {
3817                donations.push(dVal);
3818                addLine($(this).attr('name') || 'donation', $(this).data('line-name') || 'Donation', dVal);
3819            }
3820        });
3821
3822        var donation_total = donations.reduce((a,b)=>a+b,0);
3823        var grandtotal = 0;
3824        for(var i=0;i<fees.length;i++){
3825            grandtotal += parseFloat(fees[i]);
3826        }
3827        var subtotal = grandtotal - donation_total;
3828
3829        // Update displayed totals
3830        $('#subtotal').val('$'+subtotal.toFixed(2));
3831        $('#donation-total').val('$'+donation_total.toFixed(2));
3832        $('#membership-total').val('$'+(grandtotal).toFixed(2));
3833        $('#grand_total').val(grandtotal.toFixed(2));
3834
3835        // Hidden line items JSON (scoped to form)
3836        var $liField = $form.find('input[name="line_items_json"]');
3837        if(!$liField.length){
3838            $liField = $('<input type="hidden" name="line_items_json" />').appendTo($form);
3839        }
3840        $liField.val(JSON.stringify(lineItems.slice(0,30)));
3841    });
3842
3843    $('html body').on('change', '.join-form-recalcuate', function(){
3844        var fees = [];
3845        var donations = [];
3846        var fee = 0;
3847        var familyInternational = 0;
3848        var maxInternational = parseInt($('.ps0').data('internationalfamily')); 
3849        var maxInternationalReached = false;
3850        var lineItems = [];
3851        var addLine = function(id,label,amount){
3852            amount = parseFloat(amount);
3853            if(isNaN(amount) || amount <= 0) return;
3854            // Collapse duplicates (same id)
3855            var existing = lineItems.find(i=>i.id===id);
3856            if(existing){
3857                existing.unitPrice = (parseFloat(existing.unitPrice)+amount).toFixed(2);
3858            }else{
3859                var displayName = label || aercHumanizeSlug(id) || 'Fee';
3860                lineItems.push({
3861                    id: (id||'FEE'+(lineItems.length+1)).toString().replace(/[^A-Za-z0-9]/g,'').substring(0,31),
3862                    name: displayName.toString().substring(0,31),
3863                    description: displayName.toString().substring(0,255),
3864                    quantity: 1,
3865                    unitPrice: amount.toFixed(2),
3866                    taxable: false
3867                });
3868            }
3869        };
3870
3871        $('.join-form-recalcuate').each(function(){
3872            var $el = $(this);
3873            var rawName = $el.attr('name') || '';
3874            var labelText = $el.closest('.form-column').find('label[for="'+$el.attr('id')+'"]').text();
3875            var lineLabel = $el.data('line-name')
3876                || aercCleanLineLabel(labelText)
3877                || aercHumanizeSlug(rawName)
3878                || rawName;
3879            var fee = 0;
3880            var tagName = $el.prop("tagName").toLowerCase();
3881
3882            // Determine base fee value (respect data-calcvalue)
3883            if(tagName === "select") {
3884                var sel = $el.find('option:selected');
3885                if(sel.data('calcvalue') !== undefined) {
3886                    fee = parseFloat(sel.data('calcvalue'));
3887                } else if(sel.attr('value')) {
3888                    fee = parseFloat(sel.attr('value'));
3889                }
3890            } else {
3891                if($el.data('calcvalue') !== undefined) {
3892                    fee = parseFloat($el.data('calcvalue'));
3893                } else if($el.val() !== '') {
3894                    fee = parseFloat($el.val());
3895                }
3896            }
3897
3898            if(isNaN(fee)) fee = 0;
3899
3900            // Additional horse logic (first free)
3901            if($el.hasClass('additionalHorseFeeVal')) {
3902                // free if not cloned-group
3903                if(!$el.closest('.equine-clone').hasClass('cloned-group')) {
3904                    fee = 0;
3905                }
3906                // free if the horse-name input in this row is blank — prevents
3907                // charging for accidentally-cloned, never-filled-in horse rows.
3908                var $primaryName = $el.closest('.equine-clone').find('input').filter(function(){
3909                    return /\['name'\]$/.test(this.name || '');
3910                }).first();
3911                if(!$primaryName.length || $.trim($primaryName.val() || '') 
3911=== '') {
3912                    fee = 0;
3913                }
3914            }
3915            if($el.hasClass('additionalFamilyHorseFeeVal')) {
3916                if(!$el.closest('.family-equine-clone').hasClass('cloned-group')) {
3917                    fee = 0;
3918                }
3919                var $familyName = $el.closest('.family-equine-clone').find('input').filter(function(){
3920                    return /\['name'\]$/.test(this.name || '');
3921                }).first();
3922                if(!$familyName.length || $.trim($familyName.val() || '') === '') {
3923                    fee = 0;
3924                }
3925            }
3926
3927            // International family cap logic
3928            if($el.hasClass('aercInternational') && !maxInternationalReached){
3929                familyInternational += parseInt(fee||0);
3930                if(familyInternational > maxInternational) {
3931                    // over cap: remove the excess just added
3932                    fee = 0;
3933                    familyInternational = maxInternational;
3934                    maxInternationalReached = true;
3935                }
3936                if(familyInternational === maxInternational) {
3937                    maxInternationalReached = true;
3938                }
3939            } else if($el.hasClass('aercInternational')) {
3940                fee = 0;
3941            }
3942
3943            // Donations tracked separately (assume elements with .donations)
3944            if($el.hasClass('donations')) {
3945                if(fee > 0) donations.push(fee);
3946                addLine(rawName || 'donation', lineLabel, fee);
3947                return; // continue loop
3948            }
3949
3950            // Skip non-positive
3951            if(fee > 0) {
3952                fees.push(fee);
3953                addLine(rawName || 'fee_'+fees.length, lineLabel, fee);
3954            }
3955        });
3956
3957        var donation_total = donations.reduce((a, b) => a + b, 0);
3958        var fees_total = fees.reduce((a, b) => a + b, 0);
3959        var grandtotal = fees_total + donation_total;
3960        var subtotal = fees_total;
3961
3962        $('#subtotal').val('$'+subtotal.toFixed(2));
3963        $('#donation-total').val('$'+donation_total.toFixed(2));
3964        $('#membership-total').val('$'+grandtotal.toFixed(2));
3965        $('#grand_total').val(grandtotal.toFixed(2));
3966
3967        // Ensure hidden input exists
3968        var $liField = $('#line_items_json');
3969        if(!$liField.length) {
3970            $liField = $('<input type="hidden" id="line_items_json" name="line_items_json" />').appendTo('#aerc_join_form, #aerc_renewal');
3971        }
3972        $liField.val(JSON.stringify(lineItems.slice(0,30))); // enforce 30 max
3973    });
3974
3975	$('html body').on('click', '.no-toggle', function(e){
3976		e.preventDefault();
3977		$(this).closest('.toggle-group').find('.yes-toggle').removeClass('active');
3978	});
3979
3980    $('html body').on('click', '.clone-horse', function(e){
3981		e.preventDefault();
3982		var thisbtn = $(this);
3983		var dupWrapper = $(this).closest('.equine-clone');
3984		var clone = dupWrapper.clone();
3985		clone.find('.no-toggle').addClass('active');
3986		clone.find('.yes-toggle').removeClass('active');
3987		dupWrapper.find('.clone-horse, .clone-family').closest('.form-column').hide();
3988		var cloned = clone.insertAfter(dupWrapper);
3989		$(cloned).find('input, select, textarea').val('').attr('required', false).removeAttr('data-val data-val-required');
3990		$(cloned).find('[data-hid]').each(function(){
3991		   var thisID = $(this).data('hid');
3992		   var nextID = thisID+1;
3993		   var name = $(this).attr('name');
3994		   var newname = name.replace(thisID, nextID);
3995		   $(this).attr('name', newname);
3996		});
3997		$(cloned).find('[data-required]').each(function(){
3998			$(this).attr('required', true).attr('data-val', 'true').attr('data-val-required', 'This field is required');
3999		});
4000		$(cloned).addClass('cloned-group').prepend('<div class="remove-row" title="remove"><i class="fa fa-trash"></i></div>');
4001		$('#gold_membership').trigger('change');
4002    });
4003
4004    $('html body').on('click', '.family-clone-horse', function(e){
4005		e.preventDefault();
4006		var thisbtn = $(this);
4007		var dupWrapper = $(this).closest('.family-equine-clone');
4008		var clone = dupWrapper.clone();
4009		clone.find('.no-toggle').addClass('active');
4010		clone.find('.yes-toggle').removeClass('active');
4011		dupWrapper.find('.family-clone-horse, .clone-family').closest('.form-column').hide();
4012		var cloned = clone.insertAfter(dupWrapper);
4013		cloned.find('input, select, textarea').val('').attr('required', false).removeAttr('data-val data-val-required');
4014		cloned.find('[data-hid]').each(function(){
4015		   var thisID = $(this).data('hid');
4016		   var nextID = thisID+1;
4017		   var name = $(this).attr('name');
4018		   var newname = name.replace(thisID, nextID);
4019		   $(this).attr('name', newname);
4020		});
4021		cloned.find('[data-required]').each(function(){
4022			$(this).attr('required', true).attr('data-val', 'true').attr('data-val-required', 'This field is required');
4023		});
4024		cloned.addClass('cloned-group').prepend('<div class="remove-row" title="remove"><i class="fa fa-trash"></i></div>');
4025		$('#gold_membership').trigger('change');
4026    });
4027    $('html body').on('click', '.remove-row', function(e){
4028	if(confirm("Are you sure you want to delete this record?")){
4029	    
4030	    var prev = $(this).closest('.cloned-group');
4031		$(prev).prev().find('.clone-horse, .clone-family, .clone-distance').show();
4032		$(prev).prev().find('.clone-horse, .clone-family, .clone-distance').closest('.form-column').show();
4033		$(prev).remove();  
4034		$('#gold_membership').trigger('change');
4035	}
4036    });
4037    $('html body').on('click', '.clone-family', function(e){
4038	e.preventDefault();
4039	var thisbtn = $(this);
4040	var dupWrapper = $(this).closest('.family-clone');
4041	var clone = dupWrapper.clone();
4042	clone.find('.no-toggle').addClass('active');
4043	clone.find('.yes-toggle').removeClass('active');
4044	$('.sumo-reload')[0].sumo;
4045	dupWrapper.find('.clone-horse, .clone-family').closest('.form-column').hide();
4046	var cloned = clone.insertAfter(dupWrapper);
4047//	$('.sumo-reload')[0].sumo.unload();
4048	cloned.find('.equine-clone:eq(0)').find('.clone-horse, .clone-family').show();
4049	cloned.find('.equine-clone:not(:first)').remove();
4050	cloned.find('input, select').each(function(){
4051	   $(this).val('');
4052	});
4053	$(cloned).find('[data-hid]').each(function(){
4054    		   var thisID = $(this).data('hid');
4055    		   var nextID = thisID+1;
4056    		   var name = $(this).attr('name');
4057    		   var newname = name.replace(thisID, nextID);
4058    		   $(this).attr('name', newname);
4059    		});
4060	$(cloned).find('[data-fid]').each(function(){
4061		   var thisID = $(this).data('fid');
4062		   var nextID = thisID+1;
4063		   var name = $(this).attr('name');
4064		   var newname = name.replace(thisID, nextID);
4065		   $(this).attr('name', newname);
4066		});
4067
4068	$(cloned).addClass('cloned-group').prepend('<div class="remove-row" title="remove"><i class="fa fa-trash"></i></div>');
4069    });
4070    if($('.modal-breadcrumbs').length) {
4071        links = [];
4072    	sessionStorage.setItem("links", JSON.stringify(links));
4073    }
4074    $('html body').on('click', '.ride_retults_link', function(e){
4075	e.preventDefault();
4076	var thislink = $(this).clone();
4077	var thistext = thislink.text();
4078
4079	var backlink = JSON.parse(sessionStorage.getItem("links"));
4080
4081	backlink.push(thistext);
4082	sessionStorage.setItem("links", JSON.stringify(backlink));
4083	thislink.prepend(' Return to ').appendTo('.modal-breadcrumbs');
4084
4085
4086	$('#rideRideResults').html('<i class="icon-spinner icon-spin icon-large"></i> ');
4087	var toLoad = $(this).attr('href');
4088	$('#rideRideResults').load(toLoad+' #completedRideResults');
4089	var modal = '#rideResults';
4090	$(modal).removeClass('desactive-modal').addClass('active-modal');
4091	$cuerpo.addClass('fixed');
4092    });
4093    $('.um_update').change(function(){
4094	var $val = $(this).val();
4095	var $type = $(this).attr('id');
4096	var $user = $(this).closest('form').find('.user_id').val();
4097	$.post('/wp-admin/admin-ajax.php?action=aerc_user_meta_update', {meta_key: $type, meta_value: $val, userid: $user}, function(){
4098	    $('.ajax-msg').text('Account Updated!');
4099	   setTimeout(function(){
4100	       $('.ajax-msg').hide();
4101	   }, 2000) ;
4102	});
4103    });
4104    $('.um_update_arr').change(function(){
4105	var $cb = $(this).attr('name');
4106	var $val = $(this).closest('form').find('input[name="'+$cb+'"]:checked').map(function(){
4107	      return $(this).val();
4108	    }).get();
4109	var $type = $(this).data('type');
4110	var $user = $(this).closest('form').find('.user_id').val();
4111	$.post('/wp-admin/admin-ajax.php?action=aerc_user_meta_update', {meta_key: $type, meta_value: $val, userid: $user}, function(){
4112	    $('.ajax-msg').text('Account Updated!');
4113	    setTimeout(function(){
4114		$('.ajax-msg').hide();
4115	    }, 2000) ;
4116	});
4117    });
4118    $('#region_filter').change(function(){
4119	var region = '.'+$(this).val();
4120	$('.rn-filter').hide();
4121	$(region).show();
4122    });
4123    if($('#region_filter').length) {
4124	$('#region_filter').trigger('change');
4125    }
4126    $('.hide-seasons').hide();
4127    $('.more-seasons').click(function(e){
4128	e.preventDefault();
4129	$(this).hide();
4130	$('.hide-seasons').show();
4131    });
4132    $('.less-seasons').click(function(e){
4133	e.preventDefault();
4134	$(this).hide();
4135	$('.hide-seasons').hide();
4136	$('.more-seasons').show();
4137    });
4138    $('.calendar-season-or-date').change(function(){
4139	var val = $(this).val();
4140	var resets = $(this).data('reset');
4141	$('.csd-hide').hide();
4142	if(resets == 'date-reset') {
4143	    $('.date-reset').val('');
4144	}else {
4145	    $('.seasons-reset').prop('checked', false);
4146	}
4147	$(val).show();
4148    });
4149    $('.distance-check').click(function(){
4150	var $val = $(this).val();
4151	if($val == 'any') {
4152	    $('.distance-reset').prop('checked', false);
4153	}else{
4154	    $('.any-distance-reset').prop('checked', false);
4155	}
4156    });
4157    $( function() {
4158	    var dateFormat = "mm/dd/yy",
4159	      from = $( "#date-from" )
4160	        .datepicker({
4161	          defaultDate: "+1w",
4162	          changeMonth: true,
4163	          changeYear: true,
4164	          numberOfMonths: 1
4165	        })
4166	        .on( "change", function() {
4167	          to.datepicker( "option", "minDate", getDate( this ) );
4168	        }),
4169	      to = $( "#date-to" ).datepicker({
4170	        defaultDate: "+1w",
4171	        changeMonth: true,
4172	        changeYear: true,
4173	        numberOfMonths: 1
4174	      })
4175	      .on( "change", function() {
4176	        from.datepicker( "option", "maxDate", getDate( this ) );
4177	      });
4178	 
4179	    function getDate( element ) {
4180	      var date;
4181	      try {
4182	        date = $.datepicker.parseDate( dateFormat, element.value );
4183	      } catch( error ) {
4184	        date = null;
4185	      }
4186	 
4187	      return date;
4188	    }
4189    });
4190
4191    $('html body').on('click', '.pin-push', function(){
4192	var ride = '#rideRow'+$(this).data('ride');
4193	$(ride).show();
4194	var scrollTo = $(ride).offset().top - 450;
4195	$('html, body').animate({
4196            scrollTop: scrollTo
4197        }, 1000);
4198    });
4199    $('.reset-form').click(function(e){
4200	e.preventDefault();
4201	$('.reset-check').trigger('click').prop('checked', true);
4202	$('.reset-date, .reset-num').val('');
4203	$('.reset-clear').prop('checked', false);
4204    });
4205    $('.country-check').click(function(){
4206	if($(this).is(':checked')) {
4207	    $('.region-check').prop('checked', false);
4208	}
4209    });
4210    $('.region-check').click(function(){
4211	if($(this).is(':checked')) {
4212	    $('.country-check').prop('checked', false);
4213	}
4214    });
4215    $('html body').on('submit', '#calendar-filter', function(e){
4216    //$('#calendar-filter').submit(function(e){
4217    	e.preventDefault();
4218    	$('.calendar-results .cnt').html('<h1 class="running" style="text-align: center;"><i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i></h1>');
4219	    
4220	    var form = $(this).serialize();
4221	    
4222	    var formbtoa = btoa(form);
4223	    
4224	    var baseURL = {
4225		   current: window.location.pathname
4226		};
4227		
4228		//var path = window.location.pathname + '?cal=' + formbtoa;
4229		//window.history.pushState(baseURL, $('title').text(), path);
4230
4231		var scrollto = $('.calendar-results').offset().top - 250;
4232    		$('html,body').animate({
4233    		    scrollTop: scrollto
4234    		}, 700); 
4235		setTimeout(function(){
4236			$('.running').prepend('Retrieving results <br />');
4237		}, 2000);
4238		setTimeout(function(){
4239			$('.running').html('<h1 class="running" style="text-align: center;">We are adding locations to the map.<br />Refine your search parameters to load the map faster. <br /><i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i></h1>');
4240		}, 8000);
4241		setTimeout(function(){
4242			$('.running').html('<h1 class="running" style="text-align: center;">Apologies for the wait -- still adding markers to the map.<br />Refine your search parameters to load the map faster. <br /><i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i></h1>');
4243		}, 14000);
4244		setTimeout(function(){
4245			$('.running').html('<h1 class="running" style="text-align: center;">Still adding markers to the map.<br />Refine your search parameters to load the map faster. <br /><i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i></h1>');
4246		}, 21000);
4247		setTimeout(function(){
4248			$('.running').html('<h1 class="running" style="text-align: center;">Almost done... <br />Refine your search parameters to load the map faster. <br /><i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i></h1>');
4249		}, 30000);
4250    	$.post('/wp-admin/admin-ajax.php?action=aerc_calendar_form', form, function(data){
4251			if(data.btoa) {
4252				path = window.location.pathname + '?calID=' + data.btoa;
4253				window.history.pushState(baseURL, $('title').text(), path);
4254			}
4255    		if(data.html) {
4256    			$('.calendar-results .cnt').html(data.html);
4257				$('html, body').animate({
4258                    scrollTop: $(".thisDate").offset().top - 150
4259                }, 100);
4260    		} else {
4261    			$('.calendar-results .cnt').html('<strong>Sorry, nothing matched your search request.  Please consider expanding your search.</strong>');
4262    		}
4263    	});
4264    });
4265    if($('.load_personal_calendar').length) {
4266	$.get('/wp-admin/admin-ajax.php?action=aerc_personal_calendar', function(data){
4267	    if(data.html) {
4268		$('.load_personal_calendar .cnt').html(data.html);
4269	    }
4270	});
4271    }
4272    if($('.load_big_rides').length) {
4273	$.get('/wp-admin/admin-ajax.php?action=aerc_hundred_mile', function(data){
4274	    if(data.html) {
4275		$('.load_big_rides .cnt').html(data.html);
4276	    }
4277	});
4278    }
4279    $('.sq_label').click(function(){
4280    	$(this).hide();
4281    });
4282    // Time-to-fill: stamp the form on render. Server requires >= 2s elapsed
4283    // and rejects POSTs missing this field — bots that don't run our JS fail.
4284    $('#subscribe_ts').val(Date.now());
4285    $('#subscribe_button').click(function(e){
4286    	e.preventDefault();
4287    	$('#subscribe_success').text('');
4288    	var email = $('#subscribe_email').val();
4289    	var website = $('#subscribe_website').val();
4290    	var ts = $('#subscribe_ts').val();
4291    	$.post('/wp-admin/admin-ajax.php?action=aerc_subscribe', {email: email, website: website, ts: ts}, function(data){
4292    		if(data.success){
4293    			$("#subscribe_success").text(data.msg);
4294    			$("#subscribe_email").val('');
4295    		}
4296    	});
4297    });
4298    $('#aerc_horse_register').validate();
4299    $('#aerc_join_form').validate();
4300	$(document).on("focus", ".phone-mask", function() { 
4301	    $(this).mask('000-000-0000');
4302	  });
4303    $('#sancUorC').change(function(){
4304	var value = $(this).find('option:selected').attr('value');
4305	console.log(value);
4306	if(value == 'Canada') {
4307	    $('.show-if-canada').show();
4308	}else{
4309	    $('.show-if-canada').hide();
4310	}
4311    });
4312    $('.award-link').click(function(e){
4313	e.preventDefault();
4314	var season = $(this).closest('form').find('#year').find('option:selected').attr('value');
4315	var report = $(this).data('report');
4316	$('.aerc-reports-cnt .cnt').html('<h1 style="text-align: center;"><i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i><br />Click only once - hold your horses!</h1>');
4317    	$.post('/wp-admin/admin-ajax.php?action=aerc_reports_form', {season: season, report: report}, function(data){
4318    	    if(data.html) {
4319    		$('.aerc-reports-cnt .cnt').html(data.html);
4320    	    }
4321    	    if(data.heading){
4322    		$('.aerc-reports-cnt h3').text(data.heading);
4323    	    }
4324    	});
4325    });
4326	$('.show-family').click(function(){
4327		$('.show-on-family-add').find('[data-required]').attr('required', false).removeAttr('data-val data-val-required');
4328		if($(this).data('value') == 'yes') {
4329			$('.show-on-family-add').show();
4330			$('.show-on-family-add').find('[data-required]').attr('required', true).attr('data-val', 'true').attr('data-val-required', 'This field is required');
4331		}else{
4332			$('.show-on-family-add').hide();
4333			// Same reason as .btn-toggle 'no' branch: hidden inputs still serialize.
4334			$('.show-on-family-add').find('input[type="text"], input[type="email"], input[type="tel"], input[type="number"], input[type="date"], textarea').val('');
4335			$('.show-on-family-add').find('select').prop('selectedIndex', 0);
4336			$('.show-on-family-add').find('input[type="checkbox"], input[type="radio"]').prop('checked', false);
4337		}
4338	});
4339	if($('#clone_family_renew').length) {
4340		let toclone = btoa($('.renewal_clone_group').last().get(0).outerHTML);
4341		sessionStorage.setItem('aerc_cloned_renew_family', toclone);
4342		var tochange = $('#clone_family_renew');
4343		//if($('.gp-id').val() == ''){
4344			$(tochange).find('option[value="0"]').attr('selected', 'selected');
4345			clone_family_renew(tochange);
4346		//}
4347    }
4348    $('#clone_family_renew').change(function(){
4349		clone_family_renew($(this));
4350	});
4351	function clone_family_renew(el){
4352    	var cnt = $(el).find('option:selected').attr('value');
4353        if(cnt > 0 ){
4354			$('.member_relation_hidden').show();
4355			if($('#relation').val() == ''){
4356				$('#relation').focus();
4357				$('html, body').animate({ scrollTop: $("#relation").offset().top }, 500);
4358			}
4359		}else{
4360			if($('.edit-group').length == 1) {
4361			$('.member_relation_hidden').hide();
4362				
4363			}
4364		}
4365
4366    	var current = $('.renewal_clone_group').length;
4367		var get_cloned = sessionStorage.getItem('aerc_cloned_renew_family');
4368		var clone = '';
4369		if(get_cloned) {
4370			clone = atob(get_cloned);
4371		}else{
4372			var dupWrapper = $('.renewal_clone_group').last().get(0).outerHTML;
4373			var clone = dupWrapper.clone();
4374		}
4375    	if(current < cnt) {
4376    		//we need to add some
4377
4378			//we can add the address from the main profile
4379
4380			var address_1 = $('#address_1').val();
4381			var address_2 = $('#address_2').val();
4382			var city = $('#city').val();
4383			var state = $('#state').val();
4384			var zip = $('#zip').val();
4385			var country = $('#country').val();
4386			var elVal = '';
4387
4388    		for(var i = current; i < cnt; i++ ) {
4389    			var cloned = $('.insert-cloned').append(clone);
4390    			cloned.find('input, select').each(function(){
4391					   elVal = '';
4392					   if($(this).attr('name') == 'family_member_address_1[]'){
4393						  elVal = address_1;
4394					   }
4395					   if($(this).attr('name') == 'family_member_address_2[]'){
4396						  elVal = address_2;
4397					   }
4398					   if($(this).attr('name') == 'family_member_city[]'){
4399						  elVal = city;
4400					   }
4401					   if($(this).attr('name') == 'family_member_state[]'){
4402						  elVal = state;
4403					   }
4404					   if($(this).attr('name') == 'family_member_zip[]'){
4405						  elVal = zip;
4406					   }
4407					   if($(this).attr('name') == 'family_member_country[]'){
4408						  elVal = country;
4409					   }
4410	
4411    				   $(this).val(elVal);
4412    				});
4413				
4414    		}
4415    	} else {
4416			//we cannot remove the last one
4417			
4418    		if(current != cnt) {
4419    			//we need to remove some
4420    			for(i = current; i > cnt; i--) {
4421    				$('.renewal_clone_group').last().remove();
4422    			}
4423    		}
4424    	}
4425    }
4426    $(".edit-group input, .edit-group select").change(function(){
4427    	var id = $(this).closest('.edit-group').find('.gp-id').val();
4428    	var field = $(this).attr('name');
4429    	var value = $(this).val();
4430    	if(value.length == 0) {
4431    		value = $(this).find('option:selected').attr('value');
4432    	}
4433    	// $.post('/wp-admin/admin-ajax.php?action=aerc_renew_form_update', {id: id, field: field, value: value}, function(){
4434    		
4435    	// });
4436    });
4437    $('html body').on("change", ".add_family_member input, .add_family_member select", function(){
4438    	var gpid = $(this).closest('.add_family_member').find('.gp-id');
4439    	var id = $(this).closest('.add_family_member').find('.gp-id').val();
4440    	var field = $(this).attr('name');
4441    	var value = $(this).val();
4442    	if(value.length == 0) {
4443    		value = $(this).find('option:selected').attr('value');
4444    	}
4445    	var family = '';
4446    	if(id.length == 0) {
4447    		family = $('#family_id').val();
4448    	}
4449    	$.post('/wp-admin/admin-ajax.php?action=aerc_renew_form_update', {id: id, field: field, value: value, family: family}, function(data){
4450    		if(data.insert_id) {
4451    			$(gpid).val(data.insert_id);
4452    		}
4453    	});
4454    }); 
4455    $('.fee-radio').change(function(){
4456	$('.hidden-till-fee-selected').slideDown('slow');
4457	//add the fees
4458	var adultFee = $(this).data('adult');
4459	var youthFee = $(this).data('youth');
4460	var judgeFee = $(this).data('judge');
4461	var subFee = $(this).data('sub');
4462	var canadamailingFee = $(this).data('canadamailing');
4463	var internationalmailingFee = $(this).data('internationalmailing');
4464	var additionalHorseFee = $(this).data('additionalhorsefee');
4465	var goldSingle = $(this).data('goldsingle');
4466	var goldFamily = $(this).data('goldfamily');
4467	$('.adultFeeVal').text('Adult Member (age 18 or older): $'+adultFee);
4468	$('.adultFeeVal').attr('data-calcvalue', adultFee);
4469	$('.youthFeeVal').text('Youth Member (17 or younger as of 12/1/18): $'+youthFee);
4470	$('.youthFeeVal').attr('data-calcvalue', youthFee);
4471	$('.judgeFeeVal').text('Control Judge Membership (non-riding): $'+judgeFee+'; Licensed Veterinarians only');
4472	$('.judgeFeeVal').attr('data-calcvalue', judgeFee);
4473	$('.subFeeVal').text('12 Month Subscription to Endurance News only (non-riding) – one year: $'+subFee);
4474	$('.subFeeVal').attr('data-calcvalue', subFee);
4475	$('.canadamailingFeeVal').text('Canada ($'+canadamailingFee+' additional mailing cost)');
4476	$('.canadamailingFeeVal').attr('data-calcvalue', canadamailingFee);
4477	$('.internationalmailingFeeVal').text('A country other than the U.S. or Canada ($'+internationalmailingFee+' additional mailing cost)');
4478	$('.internationalmailingFeeVal').attr('data-calcvalue', internationalmailingFee);
4479	$('.additionalHorseFeeVal').attr('data-calcvalue', additionalHorseFee);
4480	$('.additionalFamilyHorseFeeVal').attr('data-calcvalue', additionalHorseFee);
4481	$('.goldsingleFee').text('Primary/Single -- $'+goldSingle);
4482	$('.goldsingleFee').attr('data-calcvalue', goldSingle);
4483	$('.goldfamilyFee').text('All AERC immediate family members - $'+goldFamily);
4484	$('.goldfamilyFee').attr('data-calcvalue', goldFamily);
4485    });
4486    
4487    $('.my-horse').click(function(e){
4488	e.preventDefault();
4489	var id = $(this).data('id');
4490	console.log(id);
4491	$('.dirctory-results .cnt').html('<h1 style="text-align: center;"><i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i><br />Click only once - hold your horses!</h1>');
4492	if($(this).hasClass('horse-record')) {
4493	  //return the record
4494	    $.get('/wp-admin/admin-ajax.php?action=aerc_equine_record&id='+id, function(data){
4495    		if(data.success) {
4496			$('.dirctory-results .cnt').html(data.html);
4497		}
4498	    });
4499	} else {
4500	    console.log('fell')
4501	    //return the edit form
4502	    	$.post('/wp-admin/admin-ajax.php?action=aerc_equine_update_form', {id: id}, function(data){
4503	    		if(data.success) {
4504	    			$('.dirctory-results .cnt').html(data.html);
4505	    		}
4506	    	});
4507	}
4508    });
4509    
4510    $(window).load(function(){
4511	    if($('.equal-rows').length > 0) {
4512	    	var singleImg = 0;
4513	    	var thisSingleImg = 0;
4514	    	var textcontent = 0;
4515	    	var thisTextcontent = 0;
4516	    	
4517	        $('.sponsor-block').each(function(){
4518	            thisSingleImg = $(this).find('.wpb_single_image img').outerHeight();
4519	            
4520	            if(thisSingleImg > singleImg) {
4521	        	singleImg = thisSingleImg;
4522	        	$('.equal-rows .wpb_single_image').height(singleImg);
4523	            }
4524	    	    thisTextcontent = $(this).find('.wpb_text_column.wpb_content_element .wpb_wrapper').outerHeight();
4525	    	    if(thisTextcontent > textcontent){
4526	    		textcontent = thisTextcontent;
4527	    		$('.equal-rows .wpb_text_column.wpb_content_element').height(textcontent);
4528	    	    }
4529	    		
4530	        });	
4531	    }	
4532    });
4533
4534	//Remove the weird search form loading
4535	const getCurrentUrl = $(location).attr('href');
4536	const sanctionRide = 'https://aerc.org/compete/sanction-a-ride'
4537	const sactionRideHttp = 'https://aerc.org/compete/sanction-a-ride';
4538	const horseInfo = 'https://aerc.org/membership/my-horse-info/';
4539	const horseInfoHttp = 'https://aerc.org/membership/my-horse-info/';
4540	const myProfile = 'https://aerc.org/membership/profile';
4541	const myProfileHttp = 'https://aerc.org/membership/profile';
4542	if (getCurrentUrl === sanctionRide ||  getCurrentUrl === horseInfo ||  getCurrentUrl === myProfile || getCurrentUrl === sactionRideHttp || getCurrentUrl === horseInfoHttp || getCurrentUrl === myProfileHttp){
4543		$('.cat-search-bar.gwr').css('display', 'none');
4544		$('.gwr.loading-icon').css('display', 'none');
4545		$('#ms-container').css('display', 'none');
4546	}
4547
4548	//export region data to csv
4549
4550	$('.download_csv').click(function (e) {
4551		e.preventDefault();
4552		
4553		const region_code = 'region='+$('select[name="region"]').val();
4554		const region_code_int = $('select[name="region"]').val();
4555	
4556		const regionCode = [{code: 1, name :'Central'}, {code: 2, name:'Midwest'} ,{code :3, name :'Mountain'}, {code: 7, name: 'Northeast'}, {code: 8, name: 'Northwest'}, {code : 9, name: 'Pacific Southwest'}, {code : 10, name :'Southeast'}, {code: 11, name: 'Southwest'}, {code : 12, name: 'West'}, {code : 13, name: 'International – outside U.S. or Canada'}, {code: 14, name :'Unknown'},];
4557
4558		const mappedRegionCode = regionCode.map(data => {
4559			if(data.code == region_code_int) {
4560				return data.name;
4561			}
4562		});
4563		$('.dirctory-results .cnt').html('<h1 style="text-align: center;"  class="spinnerCSV"><i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i><br />Click only once - hold your horses!</h1>');
4564		$.post('/wp-admin/admin-ajax.php?action=aerc_paid_members_downloadable_csv',region_code, data => {
4565				
4566				if(data) {
4567					$('.spinnerCSV i').css('display', 'none');
4568					$('.spinnerCSV').text(`${mappedRegionCode.join("")} Region CSV Downloaded Successfully`);
4569					const res = {data :data.res};
4570					const sortedArrNames = res.data.name;
4571					sortedArrNames.sort(arrNamesFunc);
4572					function arrNamesFunc(a, b){
4573							if (a[2] === b[2]) {
4574									return 0;
4575							}
4576							else {
4577									return (a[2] < b[2]) ? -1 : 1;
4578							}
4579					}
4580					const arrNames = sortedArrNames;
4581					const arrIds = res.data.id;
4582					let csv = "";
4583					const titles = ['ExternalMemberID', 'MemberType', 'LastName', 'FirstName', 'DivisionCode', 'City', 'StateCode'];
4584					csv = `Member current dues status for the ${mappedRegionCode.join("")} reigon.`+"\n" + titles +',' +'\t' + titles + "\n\n";
4585					for(let i = 0; i < arrNames.length; i++) {
4586						csv += arrIds[i].join() + ','+ '\t';
4587						csv += arrNames[i].join();
4588						csv += "\n";
4589					}
4590					const csvDownload = (content, fileName, mimeType) => {
4591						mimeType = mimeType || 'application/octet-stream';
4592						const a = document.createElement('a');
4593						if (navigator.msSaveBlob) { 
4594							navigator.msSaveBlob(new Blob([content], {
4595								type: mimeType
4596							}), fileName);
4597						} else if (URL && 'download' in a) { 
4598							a.href = URL.createObjectURL(new Blob([content], {
4599								type: mimeType
4600							}));
4601							a.setAttribute('download', fileName);
4602							document.body.appendChild(a);
4603							a.click();
4604							document.body.removeChild(a);
4605						} else {
4606							location.href = 'data:application/octet-stream,' + encodeURIComponent(content); 
4607						}
4608					}
4609					csvDownload(csv, `PaidMemberListing_${mappedRegionCode.join("")}_region.csv`, 'text/csv;encoding:utf-8');
4610				}
4611		});
4612		const scrollto = $('.dirctory-results').offset().top - 250;
4613		$('html,body').animate({
4614				scrollTop: scrollto
4615		}, 700);
4616	});
4617
4618
4619	//validate primary phone
4620	/*
4621	$('#phone_home').keypress(function (e) {
4622
4623		if(!/[0-9]/.test(String.fromCharCode(e.which))) return false;
4624
4625		let value = $(this).val();
4626		if(value == '') return;
4627		value = $(this).val().split("-").join("");
4628	
4629		if (value.length < 10) {
4630			value = value.match(new RegExp('.{1,3}', 'g')).join("-");				
4631		}else {
4632			return false;
4633		}
4634			$(this).val(value);
4635
4636	});
4637	//validate secondary phone
4638	$('#phone_cell').keypress(function (e) {
4639
4640		if(!/[0-9]/.test(String.fromCharCode(e.which))) return false;
4641
4642		let value = $(this).val();
4643		if(value == '') return;
4644		value = $(this).val().split("-").join("");
4645	
4646		if (value.length < 10) {
4647			value = value.match(new RegExp('.{1,3}', 'g')).join("-");				
4648		}else {
4649			return false;
4650		}
4651			$(this).val(value);
4652
4653	});
4654	*/
4655	//annual ride stats
4656	$('html body').on('click', '.arsTab', function(e){
4657		e.preventDefault();
4658		var thislink = $(this).find('a');
4659		var thisTab = $(thislink).closest('li');
4660		var type = $(thislink).data('type');
4661		$('.arsTab').removeClass('active-tab');
4662		$(thisTab).addClass('active-tab');
4663		$('.row_for_tabs').hide();
4664		if(type == 'all') {
4665			$('.row_for_tabs').show();
4666		}
4667		if(type == 'region') {
4668			$('.region_labels_tab_row').show();
4669		}
4670		if(type == 'distance') {
4671			$('.distances_tab_row').show();
4672		}
4673		if(type == 'annual') {
4674			$('.annual_tabs_row').show();
4675		}
4676		
4677	});
4678	//toggle the total points display
4679	$('html body').on('click', '#show_more', function(e){
4680//	$('#show_more').click(function(e) {
4681		e.preventDefault();
4682		this.expand = !this.expand;
4683		$(this).text(this.expand?"Show less":"Show more ...");
4684		$('.aerc_display_points').find('.more, .less').toggleClass('more less');
4685	});
4686	// toggle the recent ride results display
4687	$('#show_recent_results').click(function(e) {
4688		e.preventDefault();
4689		this.expand = !this.expand;
4690		$(this).text(this.expand?"Show less":"Show more ...");
4691		$('.more-display-results').find('.more-results, .less').toggleClass('more-results less');
4692	});
4693	
4694	$(document).click(function() {
4695		// all dropdowns
4696		$('.wrapper-dropdown').removeClass('active');
4697	});
4698	
4699	$('.wrapper-dropdown').click(function(e){
4700		$(this).toggleClass('active');
4701		e.stopPropagation();
4702	});
4703	var sanctionDay = $('.clone-this.original');
4704	$(sanctionDay).appendTo('footer');
4705	var clonedSanctionForm = $(sanctionDay).clone(true).get(0);
4706	$('.dropdown-item a').click(function(e){
4707		e.preventDefault();
4708		var content = '';
4709		var thisWrapper = $(this).closest('#dd');
4710		var days = $(this).data('value');
4711		var wrapperTop = '<div class="tabs do-not-save">';
4712		$(thisWrapper).closest('form').find('.tabs').remove();
4713		$(thisWrapper).closest('form').find('.clone-this').remove();
4714		var i = 1;
4715		var thisClone = [];
4716		while(i<=days){
4717			var tabclass = 'active';
4718			if(i>1) {
4719				tabclass = '';
4720			}
4721			wrapperTop += '<a class="days-distance-tab '+tabclass+'" href="#selectdistance'+i+'">Day '+i+'</a>';
4722			var sanctionClone = $(clonedSanctionForm).clone(true).get(0);
4723			thisClone.push(sanctionClone);
4724			i++;
4725		}
4726		i = 1;
4727		$(thisClone).each(function(){
4728			$(this).attr("id", "selectdistance"+i).attr('data-dist', i);
4729			$(this).find('.days-for-print').text('Day '+i);
4730			var dayletter = '';
4731			if(i == 1) {
4732				$(this).removeClass('hidden original');
4733				dayletter = 'a';
4734			} else {
4735				$(this).removeClass('original');
4736				if(i == 2) {
4737					dayletter = 'b';
4738				}
4739				if(i == 3) {
4740					dayletter = 'c';
4741				}	
4742				if(i == 4) {
4743					dayletter = 'd';
4744				}
4745			}
4746			
4747			// adjust the name of each of the items
4748			$(this).find('select, input').each(function(){
4749				$(this).attr('name', $(this).attr('name')+'['+dayletter+']');
4750			});
4751			$(this).appendTo('#days-wrapper');
4752			$(this).find('.distanceday').val(i).attr('value', i);
4753			i++;
4754		});
4755		var formdata = wrapperTop+'</div>';
4756		$(formdata).prependTo('#days-wrapper');
4757	});
4758	$('html body').on('blur', '.distancepair', function(){
4759		var fee = 0;
4760		$.get('/wp-admin/admin-ajax.php?action=aerc_get_option_fee&type=sanction', function(fees){
4761			var firstDistance = parseInt(fees.aerc_price_sanction_first_distance);
4762			var otherDistances = parseInt(fees.aerc_price_sanction_additional_distance);
4763			var equineCanada = parseInt(fees.aerc_price_sanction_equine_canada_fee);
4764			$('.distancepair[type="date"]').each(function(){
4765				if($(this).val() != '') {
4766					//every name that contains an "0" is $25 all others are $10
4767					if($(this).is("[name*='0']")){
4768						fee += firstDistance;
4769					}else{
4770						fee += otherDistances;
4771					}
4772				}
4773			});
4774			
4775			//if($('.equine_canada_select').val() == 'My ride will NOT be sanctioned with Equine Canada'){
4776				//fee += equineCanada;
4777			//}
4778			$('#grand_total').val(fee);			
4779		});
4780
4781	});
4782	$('#days-wrapper').on('click', '.days-distance-tab', function(e){
4783		e.preventDefault();
4784		$('.days-distance-tab').removeClass('active');
4785		$(this).addClass('active');
4786		var tab = $(this).attr('href');
4787		$('.clone-this').hide();
4788		$(tab).show('slow');
4789	});
4790	$(document).click(function() {
4791		// all dropdowns
4792		$('.wrapper-dropdown').removeClass('active');
4793	});
4794	$('#membership_type').change(function(){
4795		$('.vet-yes-no, .subscripton-only-cntr').show();
4796				$('#membership_division_main').attr('required', true);
4797		if($(this).children("option:selected").val() == '1') {
4798			$('.vet-yes-no').show();
4799		} else {
4800			if($(this).children("option:selected").val() == '3') {
4801				$('.vet-yes-no, .subscripton-only-cntr').hide();
4802				$('#membership_division_main').attr('required', false).val(7);
4803				
4804			}
4805			if($(this).children("option:selected").val() == '2') {
4806				$('#dmv').val(1).trigger('change');
4807			}
4808			$('.vet-yes-no').hide();
4809		}
4810	});
4811	/* disable printable area for now
4812	$('html body').on('click', '.printthis', function(){
4813		 var cnt = $(this).closest('.aerc-panel').clone();
4814		 $('#print-me').html(cnt);
4815		 window.print();
4816	 });
4817	*/
4818	$('.family-change-division').change(function(){
4819	    var mt = $(this).find('option:selected').attr('value');
4820	    if(mt == '1') {
4821		$(this).closest('.family-clone').find('.membership-division-family option').show();
4822		$(this).closest('.family-clone').find('.division-hidden-by-membership-type-5, .division-hidden-by-membership-type-6').hide();
4823	    }else {
4824		if(mt == '6') {
4825		    $(this).closest('.family-clone').find('.membership-division-family option').show();
4826		    $(this).closest('.family-clone').find('.division-hidden-by-membership-type-1, .division-hidden-by-membership-type-2, .division-hidden-by-membership-type-3, .division-hidden-by-membership-type-4, .division-hidden-by-membership-type-7').hide();
4827		}
4828	    }	  
4829	});
4830	
4831	$('html body').on('change', '.family-change-division', function(e){
4832	    var mt = $(this).find('option:selected').attr('value');
4833	    if(mt == '1') {
4834		$(this).closest('.family-clone').find('.membership-division-family option').show();
4835		$(this).closest('.family-clone').find('.division-hidden-by-membership-type-5, .division-hidden-by-membership-type-6').hide();
4836	    }else {
4837		if(mt == '6') {
4838		    $(this).closest('.family-clone').find('.membership-division-family option').show();
4839		    $(this).closest('.family-clone').find('.division-hidden-by-membership-type-1, .division-hidden-by-membership-type-2, .division-hidden-by-membership-type-3, .division-hidden-by-membership-type-4, .division-hidden-by-membership-type-7').hide();
4840		}
4841	    }	
4842	});
4843	$('html body').on('change', '.sanction-distance-group .distancepair', function(){
4844		var thisgroup = $(this).closest('.sanction-distance-group');
4845		var distance = $(thisgroup).find('.distancedistance').val();
4846		var disttype = $(thisgroup).find('.distancetype').val();
4847		if(distance > 10) {
4848			if(distance < 45 && disttype) {
4849				if(disttype != 'Limited Distance') {
4850					alert('Please check your Distance Type and Distance!');
4851				}
4852			}else{
4853				if(disttype && disttype == 'Limited Distance'){
4854					alert('Please check your Distance Type and Distance!');
4855				}
4856			}
4857		}
4858	});
4859	if($('.logged-in.aerc-not-current .current-member-only').length){
4860		
4861		$('.aerc-not-current .current-member-only .gwr:not(".aerc-panel")').remove();
4862	}
4863	
4864	if($('.aerc-not-current .current-member-only').length){
4865		if($('body').hasClass('logged-in')) {
4866			var logout = '';
4867			$('.aerc-not-current .current-member-only .cnt').each(function(){
4868				if($(this).closest('.current-member-only').hasClass('add-logout')){
4869					logout = '<br><br><br><a href="/wp-login.php?action=logout">Log Out</a>';
4870				}		
4871				$(this).html('<div class="blue-links" style="text-align: center;">This content is only available to paid members. <a href="/compete/renew-option/">Please click here to renew</a>'+logout+'</div>');
4872			});
4873		}else{
4874			$('.aerc-not-current .current-member-only .cnt').html('<div class="blue-links" style="text-align: center;">This content is only available to paid members. <a href="#" class="call-login">Please click here to login</a></div>');
4875		}
4876		$('.aerc-not-current .current-member-only .gwr:not(".aerc-panel")').remove();
4877	}
4878	
4879	$(window).scroll(function() {
4880	    var height = $(window).scrollTop();
4881
4882	    if(height  > 250) {
4883	        $('.nav-wrapper').addClass('fixed-menu');
4884	    }else{
4885	    	$('.nav-wrapper').removeClass('fixed-menu');
4886	    }
4887	});
4888	
4889	var activate = getUrlParameter('activate');
4890	
4891	if(activate){
4892		active_modal($('#mdl_activate_member'));
4893	}
4894	
4895	function getUrlParameter(sParam) {
4896	    var sPageURL = window.location.search.substring(1),
4897	        sURLVariables = sPageURL.split('&'),
4898	        sParameterName,
4899	        i;
4900	
4901	    for (i = 0; i < sURLVariables.length; i++) {
4902	        sParameterName = sURLVariables[i].split('=');
4903	
4904	        if (sParameterName[0] === sParam) {
4905	            return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
4906	        }
4907	    }
4908	    return false;
4909	};
4910	$('html body').on('click', '.tooltip-info', function(e){
4911		e.preventDefault();	
4912		if($(this).attr('href') != '#'){
4913			var link = $(this).attr('href');
4914			window.open(link, "_blank");
4915		}
4916	});
4917	// nav.mobile-menu li.menu-item-has-children > a
4918/*
4919	$('html body').on('click', 'a .mobile-menu-more', function(e){
4920		e.preventDefault();
4921		var alreadyActive = $(this).closest('li').hasClass('active');
4922		$('.m-menu nav li').removeClass('active');
4923		if(!alreadyActive){
4924			$(this).parents('li').addClass('active');	
4925		}
4926		
4927	});
4928*/
4929})( jQuery );

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.