 jQuery(document).ready(function($) {
 	if ( apbgfIsFirefox() ) {
 		jQuery( 'html' ).addClass( 'apbgf-is-firefox' );
 		apbgfEnhanceFirefoxTimeFields( '#apbgf-staff-modal' );
 	}
 	$('#apbgf_service_category').select2();
 	jQuery('#apbgf-user').select2({
		placeholder: "Select a Customer",
		allowClear: true,
		width: 'resolve'
	});
 });

 jQuery( document ).on( 'click', '#apbgf-staff-modal .apbgf-time-picker-trigger', function( e ) {
	e.preventDefault();
	e.stopPropagation();
	var $trigger = jQuery( this );
	var $input = $trigger.siblings( 'input[type="time"]' );
	if ( ! $input.length ) {
		return;
	}

	if ( apbgfIsFirefox() ) {
		var $wrapper = $trigger.closest( '.apbgf-time-input-wrap' );
		var $existing = $wrapper.find( '.apbgf-custom-time-dropdown' );

		if ( $existing.length ) {
			$existing.remove();
			jQuery( document ).off( 'click.apbgfTimeDropdown' );
			return;
		}

		// Remove any existing dropdowns first
		jQuery( '.apbgf-custom-time-dropdown' ).remove();
		jQuery( document ).off( 'click.apbgfTimeDropdown' );

		// Parse current time from input value
		var val = $input.val() || '12:00';
		var parts = val.split( ':' );
		var h24 = parseInt( parts[0], 10 ) || 0;
		var m = parseInt( parts[1], 10 ) || 0;

		var ampm = h24 >= 12 ? 'pm' : 'am';
		var h12 = h24 % 12;
		if ( h12 === 0 ) h12 = 12;

		var currentH = ( h12 < 10 ? '0' : '' ) + h12;
		var currentM = ( m < 10 ? '0' : '' ) + m;
		var currentA = ampm;

		var $dropdown = jQuery( '<div class="apbgf-custom-time-dropdown apbgf-chrome-picker"></div>' );

		var hours = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];
		var minutes = [];
		for ( var i = 0; i < 60; i++ ) {
			minutes.push( ( i < 10 ? '0' : '' ) + i );
		}
		var ampmOpts = ['am', 'pm'];

		// Create columns (no headers — items are inline like Chrome)
		var $hourCol = jQuery( '<div class="apbgf-time-column"></div>' );
		var $minCol = jQuery( '<div class="apbgf-time-column"></div>' );
		var $ampmCol = jQuery( '<div class="apbgf-time-column"></div>' );

		function updateTimeValue() {
			var hVal = parseInt( currentH, 10 );
			if ( currentA === 'pm' && hVal < 12 ) hVal += 12;
			if ( currentA === 'am' && hVal === 12 ) hVal = 0;
			var newTime = ( hVal < 10 ? '0' : '' ) + hVal + ':' + currentM;
			$input.val( newTime ).trigger( 'change' );
		}

		function setFocusedColumn( $col ) {
			$dropdown.find( '.apbgf-time-column' ).removeClass( 'focused' );
			$col.addClass( 'focused' );
		}

		// Fill Hours
		jQuery.each( hours, function( idx, hOpt ) {
			var $item = jQuery( '<div class="apbgf-time-item"></div>' ).text( hOpt );
			if ( hOpt === currentH ) {
				$item.addClass( 'selected' );
			}
			$item.on( 'click', function( itemEvent ) {
				itemEvent.preventDefault();
				itemEvent.stopPropagation();
				currentH = hOpt;
				$hourCol.find( '.selected' ).removeClass( 'selected' );
				$item.addClass( 'selected' );
				setFocusedColumn( $hourCol );
				updateTimeValue();
			} );
			$hourCol.append( $item );
		} );

		// Fill Minutes
		jQuery.each( minutes, function( idx, mOpt ) {
			var $item = jQuery( '<div class="apbgf-time-item"></div>' ).text( mOpt );
			if ( mOpt === currentM ) {
				$item.addClass( 'selected' );
			}
			$item.on( 'click', function( itemEvent ) {
				itemEvent.preventDefault();
				itemEvent.stopPropagation();
				currentM = mOpt;
				$minCol.find( '.selected' ).removeClass( 'selected' );
				$item.addClass( 'selected' );
				setFocusedColumn( $minCol );
				updateTimeValue();
			} );
			$minCol.append( $item );
		} );

		// Fill AM/PM
		jQuery.each( ampmOpts, function( idx, aOpt ) {
			var $item = jQuery( '<div class="apbgf-time-item"></div>' ).text( aOpt );
			if ( aOpt === currentA ) {
				$item.addClass( 'selected' );
			}
			$item.on( 'click', function( itemEvent ) {
				itemEvent.preventDefault();
				itemEvent.stopPropagation();
				currentA = aOpt;
				$ampmCol.find( '.selected' ).removeClass( 'selected' );
				$item.addClass( 'selected' );
				setFocusedColumn( $ampmCol );
				updateTimeValue();
			} );
			$ampmCol.append( $item );
		} );

		$dropdown.append( $hourCol ).append( $minCol ).append( $ampmCol );
		$wrapper.append( $dropdown );

		// Scroll each column to center the selected item
		setTimeout( function() {
			$dropdown.find( '.apbgf-time-column' ).each( function() {
				var $col = jQuery( this );
				var $sel = $col.find( '.selected' );
				if ( $sel.length ) {
					var colH = $col.height();
					var itemTop = $sel[0].offsetTop;
					var itemH = $sel.outerHeight();
					$col.scrollTop( itemTop - ( colH / 2 ) + ( itemH / 2 ) );
				}
			} );
		}, 30 );

		// Close dropdown when clicking outside
		setTimeout( function() {
			jQuery( document ).one( 'click.apbgfTimeDropdown', function() {
				$dropdown.remove();
			} );
		}, 10 );
	} else {
		var el = $input[0];
		el.focus();
		if ( typeof el.showPicker === 'function' ) {
			try {
				el.showPicker();
			} catch ( err ) {}
		}
	}
} );

// In Firefox, prevent default click/focus on time input and trigger the clock icon instead to open the custom picker
jQuery( document ).on( 'click focus', '#apbgf-staff-modal input[type="time"]', function( e ) {
	if ( ! apbgfIsFirefox() ) {
		return;
	}
	e.preventDefault();
	e.stopPropagation();
	var $input = jQuery( this );
	var $trigger = $input.siblings( '.apbgf-time-picker-trigger' );
	if ( $trigger.length && ! $input.closest( '.apbgf-time-input-wrap' ).find( '.apbgf-custom-time-dropdown' ).length ) {
		$trigger.trigger( 'click' );
	}
} );
 const swalWithBootstrapButtons = Swal.mixin({
 	customClass: {
 		confirmButton: 'apbgf-btn apbgf-btn-success',
 		cancelButton: 'apbgf-btn apbgf-btn-danger'
 	},
 	buttonsStyling: true
 });

 const datePickerAddHolidayField = '#datepicker';
 const datePickerRemoveHolidayField = '#datepicker-2';

 let dateRanges = [];

 const datePickerAddHolidayInvalidDate = (date) => {
 	var current_date = moment(date, 'YYYY-MM-DD').format('YYYY-MM-DD');
 	var flag = jQuery.inArray(current_date, dateRanges);
 	if ( flag >= 0 ) {				
 		return true;
 	}
 }

 const datePickerAddHolidayInvalidDateClass = (date) => {
 	var current_date = moment(date, 'YYYY-MM-DD').format('YYYY-MM-DD');
 	var flag = jQuery.inArray(current_date, dateRanges);
 	if ( flag >= 0 ) {
		
 		return 'apbgf-day-off';
 	}
 }

 const datePickerRemoveHolidayInvalidDate = (date) => {
 	var current_date = moment(date, 'YYYY-MM-DD').format('YYYY-MM-DD');	
 	if ( jQuery.inArray(current_date, dateRanges) < 0 ) {				
 		return true;
 	}
 }

 const datePickerAddHolidaySettings = {
 	parentEl: jQuery('#add_holidays'),
 	autoApply: false,
 	showDropdowns: true,	
 	alwaysShowCalendars: true,
 	linkedCalendars: true,		
 	opens: 'center',
 	minDate: moment(),
 	locale: {
 		format: 'DD-MM-YYYY',
 		separator: '_',
 		applyLabel: 'Add Holiday'			
 	},
 	isInvalidDate: datePickerAddHolidayInvalidDate,
 	isCustomDate: datePickerAddHolidayInvalidDateClass
 };

 const datePickerRemoveHolidaySettings = {
 	parentEl: jQuery('#remove_holidays'),
 	autoApply: false,
 	showDropdowns: true,	
 	alwaysShowCalendars: true,
 	linkedCalendars: true,		
 	opens: 'center',
 	minDate: moment(),
 	locale: {
 		format: 'DD-MM-YYYY',
 		separator: '_',
 		applyLabel: 'Remove Holiday'			
 	},
 	isInvalidDate: datePickerRemoveHolidayInvalidDate,	
 };

 /**
  * (Re)build holiday daterangepickers. Must run while the target tab is visible (Firefox).
  *
  * @param {string} picker 'add', 'remove', or 'both'
  */
 function apbgfInitStaffHolidayPicker( picker ) {
 	if ( ! jQuery( datePickerAddHolidayField ).length || ! jQuery( datePickerRemoveHolidayField ).length ) {
		return;
	}

 	var $add = jQuery( datePickerAddHolidayField );
 	var $remove = jQuery( datePickerRemoveHolidayField );

 	if ( 'add' === picker || 'both' === picker ) {
 		if ( $add.data( 'daterangepicker' ) ) {
 			$add.data( 'daterangepicker' ).remove();
 		}
 		$add.daterangepicker( datePickerAddHolidaySettings );
 		$add.trigger( 'click' );
 	}

 	if ( 'remove' === picker || 'both' === picker ) {
 		if ( $remove.data( 'daterangepicker' ) ) {
 			$remove.data( 'daterangepicker' ).remove();
 		}
 		$remove.daterangepicker( datePickerRemoveHolidaySettings );
		$remove.trigger( 'click' );
	}
}

/**
 * Timings tab "Add Time Slot" — do not open pro upsell for disabled start/end/add-break controls.
 *
 * @param {Element} target Event target.
 * @return {boolean}
 */
function apbgfIsStaffTimingsSlotFieldClick( target ) {
	if ( ! target || ! target.closest ) {
		return false;
	}
	return !! target.closest(
		'#apbgf-staff-form-timings .form-start-time-slots.form-time-slots-disabled, ' +
		'#apbgf-staff-form-timings .form-end-time-slots.form-time-slots-disabled, ' +
		'#apbgf-staff-form-timings .add-break-btn.form-time-slots-disabled'
	);
}

/** Keep staff Timings break panels collapsed. */
function apbgfCloseStaffTimingsBreakSections() {
	jQuery( '#apbgf-staff-form-timings .form-time-slots-break-box' ).removeClass( 'form-time-slots-break-box-show' );
}

/** Enable Add Break only for Custom Slots; disable and collapse for Full Day. */
function apbgfSyncStaffTimingsAddBreakState() {
	var $form = jQuery( '#apbgf-staff-form-timings' );
	if ( ! $form.length || ! jQuery( '#apbgf-booking_type' ).length ) {
		return;
	}
	if ( 'fullday' === jQuery( '#apbgf-booking_type' ).val() ) {
		$form.find( '.add-break-btn' ).addClass( 'form-time-slots-disabled' );
		apbgfCloseStaffTimingsBreakSections();
	} else {
		$form.find( '.add-break-btn' ).removeClass( 'form-time-slots-disabled' );
	}
}

const days = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];

 function getUrlParameter(sParam) {
 	var sPageURL = window.location.search.substring(1),
 	sURLVariables = sPageURL.split('&'),
 	sParameterName,
 	i;

 	for (i = 0; i < sURLVariables.length; i++) {
 		sParameterName = sURLVariables[i].split('=');

 		if (sParameterName[0] === sParam) {
 			return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
 		}
 	}
 	return false;
 };

 jQuery( document ).ready(function($) {

	/*Email Template Accordion*/
 	$( "#accordion" ).accordion({
 		collapsible: true,
 		heightStyle: "content",
 		animate: 200	
 	});

	/*Create Booking From Admin start*/
 	$(document).on('click', '.apbgf-add-booking', function(event) {
 		event.preventDefault();
 		
 		window.scrollTo({top: 0});
 		$('body').addClass('apbgf-modal-open');

 		$('.apbgf-response').html('').removeClass('success error');
 		if ( $('#apbgf-booking-form').length > 0 ) {
 			
 			$(`#apbgf-booking-form #apbgf-hdn-location`).val('');
 			$(`#apbgf-booking-form #apbgf-hdn-service`).val('');
 			$(`#apbgf-booking-form #apbgf-hdn-staff`).val('');
 			$(`#apbgf-booking-form #apbgf-hdn-date`).val('');
 			$(`#apbgf-booking-form #apbgf-hdn-cost`).val('');
 			$('#apbgf-booking-form')[0].reset();
 		}

 		var current = $(this);
 		var location_id = $('.apbgf_location').val();
 		var service_id = $('.apbgf_service').val();
 		var staff_id = $('.apbgf_staff').val();
 		var date = $(current).data('date');
		
 		$(`#apbgf-booking-form #apbgf-hdn-location`).val(location_id);
 		$(`#apbgf-booking-form #apbgf-hdn-service`).val(service_id);
 		$(`#apbgf-booking-form #apbgf-hdn-staff`).val(staff_id);
 		$(`#apbgf-booking-form #apbgf-hdn-date`).val(date);		

 		var data = {
 			action: 'apbgf_open_admin_booking_form',
 			nonce: apbgf_admin.nonce,
 			date: date,
 			location_id: location_id,
 			service_id: service_id,		
 			staff_id: staff_id			
 		}

 		$.ajax({
 			url: apbgf_admin.ajaxurl,
 			type: 'POST',
 			data: data,
 			beforeSend: function() {
 				$('body').append('<div id="apbgf-overlay" />');
 			},
 			success: function (response) {
 				

 				$(`#apbgf-booking-form #apbgf-hdn-cost`).val(response.price);

 				if ( response['timeslots'] && response['timeslots'].length > 0 ) {
 					var timeslots = response['timeslots'];
 					var selectElement = document.getElementById('apbgf-time');
 					selectElement.innerHTML = '';
					// Iterate over the array and create options
 					timeslots.forEach(function(value) {
 						var option = document.createElement('option');
 						option.text = value;
 						option.value = value;
 						selectElement.appendChild(option);
 					});
 				}
 				
 				var selectElement = document.getElementById('apbgf-customer');
 				selectElement.innerHTML = '';
 				var option = document.createElement('option');
 				option.text = 'Select Customer';
 				option.value = '';
 				selectElement.appendChild(option);				
 				
 				if (response && typeof response.customers === 'object' && response.customers !== null) {
					const customers = response.customers;

					if (Object.keys(customers).length > 0) {
						for (let key in customers) {
							if (customers.hasOwnProperty(key)) {
								const option = document.createElement('option');
								option.text = customers[key];
								option.value = key;
								selectElement.appendChild(option);
							}
						}
					}
				}

 				$(`#apbgf-booking-form #apbgf-show-location`).val(response.location);
 				$(`#apbgf-booking-form #apbgf-show-service`).val(response.service);
 				$(`#apbgf-booking-form #apbgf-show-staff`).val(response.staff);
 				$(`#apbgf-booking-form #apbgf-show-date`).val(response.date);

 			},
 			complete: function() {
 				$('#apbgf-overlay').remove();
				//modal to open
 				$(`#apbgf-booking-modal`).addClass('apbgf-modal-show');	
 			},
 			error: function(errorThrown) {
	            // Handle any error that occurs during the AJAX request
 				
 			}
 		});		
 	});

 	$('#apbgf-add-customer').on('click', function(event) {
 		event.preventDefault();
 		$('#apbgf-customer').val('');
 		$('#apbgf_new_customer_form').toggle();
 		if ( $('#apbgf_new_customer_form').is(':visible') ) {
 			$('#apbgf-fname').val('').attr('required', true);
 			$('#apbgf-lname').val('').attr('required', true);
 			$('#apbgf-email').val('').attr('required', true);
 			$('#apbgf-email').val('').attr('pattern', '/^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-]))+\.([a-zA-Z0-9]{2,4})+$/');
 		} else {
 			$('#apbgf-fname').val('').removeAttr('required', true);
 			$('#apbgf-lname').val('').removeAttr('required', true);
 			$('#apbgf-email').val('').removeAttr('required', true);
 			$('#apbgf-email').val('').removeAttr('pattern');
 		}
 	});

 	$('#apbgf-customer').on('change', function(event) {
 		if ( $(this).val() != '' ) {			
 			$('#apbgf-fname').val('').removeAttr('required');
 			$('#apbgf-lname').val('').removeAttr('required');
 			$('#apbgf-phone').val('');
 			$('#apbgf-email').val('').removeAttr('required');
 			$('#apbgf-email').val('').removeAttr('pattern');
 			$('#apbgf_new_customer_form').hide();
 		}		
 	});


	/*$('#apbgf-booking-form').validate({
		rules: {
		    // simple rule, converted to {required:true}
		    fname: {
		    	required: true
		    },
		    lname: {
		    	required: true
		    },
		    email: {
		    	required: true,
		    	email: true
		    },	    
		},
		highlight: function(element, errorClass) {			
			$(element).addClass('errorBorder');	
		},
		success: function (label, element) {
			$(element).removeClass('errorBorder');
		},
		submitHandler: function( form ) {			
			event.preventDefault();

			var action = 'apbgf_create_booking_admin';

			var formData = $(form).serialize() + `&action=${action}&nonce=${apbgf_admin.nonce}`;

			$.ajax({
				url: apbgf_admin.ajaxurl,
				type: 'POST',
				data: formData,
				beforeSend: function() {
					$('body').append('<div id="apbgf-overlay" />');				
				},
				success: function (response) {
					// var response = $.parseJSON(response);
					
					$('#apbgf-overlay').remove();
					swalWithBootstrapButtons.fire(
			      		response.status,
			      		response.message,
			      		response.status
			    	).then((result) => {
			    		location.reload();
			    	});
				},
				complete: function() {
					
				}
			});
		}

	});*/

 	$('#apbgf-booking-form').on('submit', function(event) {
 		event.preventDefault();

 		var action = 'apbgf_create_booking_admin';

 		var formData = $(this).serialize() + `&action=${action}&nonce=${apbgf_admin.nonce}`;

 		$.ajax({
 			url: apbgf_admin.ajaxurl,
 			type: 'POST',
 			data: formData,
 			beforeSend: function() {
 				$('body').append('<div id="apbgf-overlay" />');				
 			},
 			success: function (response) {
				// var response = $.parseJSON(response);
 				
 				$('#apbgf-overlay').remove();
 				swalWithBootstrapButtons.fire(
 					response.status,
 					response.message,
 					response.status
 					).then((result) => {
 						location.reload();
 					});
 				},
 				complete: function() {
 					
 				}
 			});
 	});
	/*Create Booking From Admin end*/


	//Email Template settings
 	$('#app_notification_form').on('submit', function(event) {
 		event.preventDefault();

 		var action = 'apbgf_email_template_settings';

 		var formData = $(this).serialize() + `&action=${action}&nonce=${apbgf_admin.nonce}`;
 		$.ajax({
 			url: apbgf_admin.ajaxurl,
 			type: 'POST',
 			data: formData,
 			beforeSend: function() {
 				$('body').append('<div id="apbgf-overlay" />');				
 			},
 			success: function (response) {
 				var response = $.parseJSON(response);
				
 				$('#apbgf-overlay').remove();
 				swalWithBootstrapButtons.fire(
 					response.status,
 					response.message,
 					response.status
 					);
 			},
 			complete: function() {
 				
 			}
 		});
 	});

	/*Dashboard Filters Starts*/

 	var start = '';
 	var end = '';

 	function applyFilterRange(start = '', end = '', flag = false) {    	
 		$('#reportrange span').html(`Select date to filter appointments`);    	
 		if ( start != '' && end != '' ) {    		
 			if ( flag ) {	        	
 				$('#reportrange span').html(`${moment(start, 'YYYY-MM-DD').format('MMMM D, YYYY')} - ${moment(end, 'YYYY-MM-DD').format('MMMM D, YYYY')}`);	        	
 			} else {	        	
 				$('#reportrange span').html(`Select date to filter appointments`);	        	
 			}
 		}
 		$('#reportrange').css({'visibility': 'visible', 'opacity': 1});      
 	}

 	$('#reportrange').daterangepicker({
 		start: moment(),
 		end: moment(),
 		ranges: {           
 			'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
 			'Today': [moment(), moment()],
 			'Tomorrow': [moment().add(1, 'days'), moment().add(1, 'days')],
 			'This Week': [moment(), moment().add(6, 'days')],           
 			'Last Week': [moment().subtract(7, 'days'), moment().subtract(1, 'days')],
 			'This Month': [moment().startOf('month'), moment().endOf('month')],
 			'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
 			'This Year': [moment().startOf('year'), moment().endOf('year')],           
 			'Last Year': [moment().subtract(1, 'year').startOf('year'), moment().subtract(1, 'year').endOf('year')]
 		}
 	}, applyFilterRange);

 	$(document).on('click', '.ranges ul li', function() {

 	});

 	var url_start = $.trim( getUrlParameter('date_from') );
 	var url_end = $.trim(getUrlParameter('date_to'));
 	
 	if ( url_start != '' && url_end != '' && url_start != 'true' && url_end != 'true' && url_start != 'false' && url_end != 'false' ) {
 			
 		applyFilterRange(url_start, url_end, true);
 	} else {		
 		
 		applyFilterRange(start, end, false);
 	}    

 	$('#reportrange').on('apply.daterangepicker', function(ev, picker) {    	
 		$('#reportrange span').html(picker.startDate.format('MMMM D, YYYY') + ' - ' + picker.endDate.format('MMMM D, YYYY'));
 		$('input[name="date_from"]').val(picker.startDate.format('YYYY-MM-DD'));
 		$('input[name="date_to"]').val(picker.endDate.format('YYYY-MM-DD'));
 		$('#post-query-submit').click();
 	});

	/*Dashboard Filters End*/

	// Add Placeholder To Search Box
 	jQuery('.search-box input[type=search]').attr('placeholder', 'Search');

 	if ( $(datePickerAddHolidayField).length > 0 && ! /firefox/i.test( navigator.userAgent ) ) {
 		apbgfInitStaffHolidayPicker( 'both' );
 	}

 	$(".close_icon").click(function(){
 		$(".gf_booking_sidebar").removeClass("activesidebar");
 		$(".gf_booking_overlayDiv").removeClass("active");
 	});
 	var apbgfSidebarPanels = ".gf_booking_general--inner, .gf_booking_display--inner, .gf_booking_apointments_listing, .gf_booking_compnay_detail, .gf_booking_email_configuration, .gf_booking_integrations--inner";

 	$("#gf_booking_cardOne").click(function(){
 		$(".gf_booking_sidebar").addClass("activesidebar");
 		$(".gf_booking_overlayDiv").addClass("active");
 		$(apbgfSidebarPanels).addClass("closed");
 		$(".gf_booking_general--inner").removeClass("closed");
 	});
 	$("#gf_booking_cardtwo").click(function(){
 		$(".gf_booking_sidebar").addClass("activesidebar");
 		$(".gf_booking_overlayDiv").addClass("active");
 		$(apbgfSidebarPanels).addClass("closed");
 		$(".gf_booking_display--inner").removeClass("closed");
 	});
 	$("#gf_bookings_appointments").click(function(){
 		$(".gf_booking_sidebar").addClass("activesidebar");
		$(".gf_booking_overlayDiv").addClass("active");
		$(apbgfSidebarPanels).addClass("closed");
		$(".gf_booking_apointments_listing").removeClass("closed");
		$(".close_icon").css("display","block");
	});
 	$("#gf_booking_company_detail").click(function(){
 		$(".gf_booking_sidebar").addClass("activesidebar");
		$(".gf_booking_overlayDiv").addClass("active");
		$(apbgfSidebarPanels).addClass("closed");
		$(".gf_booking_compnay_detail").removeClass("closed");
		$(".close_icon").css("display","block");
	});

 	$("#gf_booking_email_configuration").click(function(){
 		$(".gf_booking_sidebar").addClass("activesidebar");
		$(".gf_booking_overlayDiv").addClass("active");
		$(apbgfSidebarPanels).addClass("closed");
		$(".gf_booking_email_configuration").removeClass("closed");
		$(".close_icon").css("display","block");
	});

	// PRO Integrations sidebar with Google/Outlook/Zoom tabs
 	$("#gf_booking_integration").click(function(){
 		$(".gf_booking_sidebar").addClass("activesidebar");
 		$(".gf_booking_overlayDiv").addClass("active");
 		$(apbgfSidebarPanels).addClass("closed");
 		$(".gf_booking_integrations--inner").removeClass("closed");

 		$(".apbgf-integration-tab").removeClass("is-active active").attr("aria-selected", "false");
 		$('.apbgf-integration-tab[data-tab="google"]').addClass("is-active active").attr("aria-selected", "true");
 		$(".apbgf-integration-panel").removeClass("is-active");
 		$('.apbgf-integration-panel[data-tab-panel="google"]').addClass("is-active");
 	});

 	$(document).on("click", ".apbgf-integration-tab", function(){
 		var tab = $(this).data("tab");
 		$(".apbgf-integration-tab").removeClass("is-active active").attr("aria-selected", "false");
 		$(this).addClass("is-active active").attr("aria-selected", "true");
 		$(".apbgf-integration-panel").removeClass("is-active");
 		$('.apbgf-integration-panel[data-tab-panel="' + tab + '"]').addClass("is-active");
 	});

 	$(".gf_booking_overlayDiv").click(function(){
 		$(".gf_booking_overlayDiv").removeClass("active");
 		$(".gf_booking_sidebar").removeClass("activesidebar");
 	});

	//initializing select2
 	$('#apbgf-location').select2();

	//initializing staff time slot break select2
 	$('.apbgf-slot-break').select2();

	apbgfSyncStaffTimingsAddBreakState();

 	$(document).on('click', '.add-break-btn > span:not(.remove_spl_date)', function( e ) {
 		var $btn = $( this ).closest( '.add-break-btn' );
 		if ( $btn.closest( '#apbgf-staff-form-timings' ).length ) {
 			if ( $btn.hasClass( 'form-time-slots-disabled' ) ) {
 				e.preventDefault();
 				e.stopPropagation();
 				return false;
 			}
 		}
 		var id = $( this ).data( 'id' );
 		if ( ! id ) {
 			return;
 		}
 		$( '#break-' + id ).toggleClass( 'form-time-slots-break-box-show' );
 	});

	//Trigger to open modal 
	// add staff
 	$('.apbgf-add-button').on('click', function(event) {
 		event.preventDefault();
 		var id = $(this).data('id');
 		var isProUpsellPopup = ( id === 'apbgf-staff-pro-modal' || id === 'apbgf-location-pro-modal' );

 		window.scrollTo({top: 0});
 		$('body').addClass('apbgf-modal-open');

 		if ( ! isProUpsellPopup ) {
 			$('.apbgf-response').html('').removeClass('success error');
 			$('.modal--form')[0].reset();
 			if ( $('#apbgf-location').length > 0 ) {
 				$('#apbgf-location').trigger('change');	
 			}

 			if ( $('#apbgf-staff-form-details').length > 0 ) {
 				
 				if ( $('#apbgf-location').length > 0 ) {
 					$('#apbgf-location').trigger('change');	
 				}

 				$('#apbgf-staff-form-details')[0].reset();
 			}

 			if ( $('#apbgf-staff-form-services').length > 0 ) {
 				$('#apbgf-staff-form-services')[0].reset();
 			}

 			if ( $('#apbgf-staff-form-timings').length > 0 ) {
 				$('#apbgf-staff-form-timings')[0].reset();
 				apbgfSyncStaffTimingsAddBreakState();
 			}

 			if ( $('#apbgf-staff-form-spl-day').length > 0 ) {
 				$('#apbgf-staff-form-spl-day')[0].reset();
 			}

 			$('input[type=checkbox]').prop('checked', false);


 			if ( $('.post_id').length > 0 ) {
 				$('.post_id').val('');
 			}
 		}
		//modal to open
 		$(`#${id}`).addClass('apbgf-modal-show');

 		if ( 'apbgf-staff-modal' === id ) {
 			apbgfSyncStaffTimingsAddBreakState();
 		}

 		if ( 'apbgf-staff-modal' === id && apbgfIsFirefox() ) {
 			apbgfEnhanceFirefoxTimeFields( '#apbgf-staff-modal' );
 		}

		// new changes
		/**
		
		if(id =='apbgf-staff-modal' && apbgf_admin.staff_exists == true) {
			$(`#${id}`).addClass('apbgf-pro-modal-show');

		}
		else {

			$(`#${id}`).addClass('apbgf-modal-show');


		}
			 */

 		if ( ! isProUpsellPopup && $(datePickerAddHolidayField).length > 0 && ! apbgfIsFirefox() ) {
 			apbgfInitStaffHolidayPicker( 'both' );
 		}
 	});

	//Trigger to close modal
 	$('.modal__close').on('click', function (e) {
 		e.preventDefault();
 		var $modal = $(this).closest('.modal');
 		var parentModalStaysOpen =
 			( $modal.is('#apbgf-staff-pro-modal') && $('#apbgf-staff-modal').hasClass('apbgf-modal-show') ) ||
 			( $modal.is('#apbgf-location-pro-modal') && $('#apbgf-location-modal').hasClass('apbgf-modal-show') );

 		// Closing the pro upsell while edit modal is open: hide only the pro popup.
 		if ( parentModalStaysOpen ) {
 			e.stopPropagation();
 			$modal.removeClass('apbgf-modal-show');
 			return;
 		}

 		if ( $('.post_id').length > 0 ) {
 			$('.post_id').val('');
 		}

 		window.scrollTo({top: 0});
 		$('body').removeClass('apbgf-modal-open');

		// $(this).siblings('.modal--form')[0].reset();		
 		if ( $('.modal--form').length > 0 ) {			
 			$('.apbgf-response').html('').removeClass('success error');
 			$('.modal--form')[0].reset();

 			if ( $('#apbgf-staff-form-details').length > 0 ) {
 				if ( $('#apbgf-location').length > 0 ) {
 					$('#apbgf-location').val(null).trigger('change');	
 				}
 				
 				$('#apbgf-staff-form-details')[0].reset();
 			}

 			if ( $('#apbgf-staff-form-services').length > 0 ) {
 				$('#apbgf-staff-form-services')[0].reset();
 			}

 			if ( $('#apbgf-staff-form-timings').length > 0 ) {
 				$('#apbgf-staff-form-timings')[0].reset();
 			}

 			if ( $('#apbgf-staff-form-spl-day').length > 0 ) {
 				$('#apbgf-staff-form-spl-day')[0].reset();
 			}

 			$('input[type=checkbox]').prop('checked', false);
 		}
 		$('.modal').removeClass('apbgf-modal-show');
		// new changes
		// $('.modal').removeClass('apbgf-pro-modal-show');

 	});

	// Staff modal: clicking any disabled element or disabled section opens SVG pro popup
	// Note: some "disabled-looking" controls are implemented via CSS classes, and some areas (labels/containers)
	// are not the disabled element itself — so we detect disabled state by proximity.
	$(document).on('click pointerdown mousedown touchstart', '#apbgf-staff-modal', function(e) {
		if ( $('#apbgf-staff-pro-modal').length === 0 ) {
			return;
		}
		// Only trigger from inside the open staff modal (not when opening it).
		if ( ! $('#apbgf-staff-modal').hasClass('apbgf-modal-show') ) {
			return;
		}
		var $target = $(e.target);
		// Don't hijack close clicks.
		if ( $target.closest('.modal__close').length > 0 ) {
			return;
		}

		// Ignore programmatic clicks on hidden datepickers
		if ( $target.is('#datepicker, #datepicker-2') ) {
			return;
		}

		// Add Time Slot: start/end/add-break when disabled — no pro popup.
		if ( apbgfIsStaffTimingsSlotFieldClick( e.target ) ) {
			return;
		}

		var $closestFormCol = $target.closest('#apbgf-staff-modal .form-col-full');
		var isTimingDisabledContainer =
			$closestFormCol.find('#apbgf-duration.form-time-slots-disabled, #apbgf-interval.form-time-slots-disabled').length > 0;

		var $disabledZone = $target.closest('#apbgf-multiple_booking, #apbgf-lead-time-container, .disabled-block');
		if ( ! $disabledZone.length ) {
			$disabledZone = $target.closest( '.form-time-slots-disabled' ).filter( function() {
				return ! apbgfIsStaffTimingsSlotFieldClick( this );
			} );
		}

		var isDisabledZone =
			$disabledZone.length > 0 ||
			isTimingDisabledContainer ||
			$target.is('[disabled]');

		if ( isDisabledZone ) {
			e.preventDefault();
			e.stopPropagation();
			$('body').addClass('apbgf-modal-open');
			$('#apbgf-staff-pro-modal').addClass('apbgf-modal-show');
		}
	});

	// Capture-phase handler: attached ONLY to the staff modal so it can't interfere with list-table edit icon clicks.
	// Needed for <input type="time"> which can swallow bubbling events.
	(function() {
		var staffModal = document.getElementById('apbgf-staff-modal');
		if (!staffModal) { return; }

		function openStaffProModal() {
			jQuery('body').addClass('apbgf-modal-open');
			jQuery('#apbgf-staff-pro-modal').addClass('apbgf-modal-show');
		}

		function isDisabledZoneTarget(target) {
			if (target && (target.id === 'datepicker' || target.id === 'datepicker-2')) {
				return false;
			}
			if ( apbgfIsStaffTimingsSlotFieldClick( target ) ) {
				return false;
			}
			var proModal = document.getElementById('apbgf-staff-pro-modal');
			if (!proModal) { return false; }
			if (!staffModal.classList.contains('apbgf-modal-show')) { return false; }
			if (!staffModal.contains(target)) { return false; }
			if (target.closest && target.closest('.modal__close')) { return false; }

			var inDisabledZone =
				(target.closest && target.closest('#apbgf-multiple_booking, #apbgf-lead-time-container, .disabled-block')) ||
				(target.matches && target.matches('[disabled]'));

			if (!inDisabledZone && target.closest) {
				var disabledSlot = target.closest('.form-time-slots-disabled');
				if (disabledSlot && !apbgfIsStaffTimingsSlotFieldClick(target)) {
					inDisabledZone = true;
				}
			}

			if (!inDisabledZone && target.closest) {
				var col = target.closest('#apbgf-staff-modal .form-col-full');
				if (col && col.querySelector('#apbgf-duration.form-time-slots-disabled, #apbgf-interval.form-time-slots-disabled')) {
					inDisabledZone = true;
				}
			}

			return !!inDisabledZone;
		}

		function captureHandler(e) {
			if (isDisabledZoneTarget(e.target)) {
				e.preventDefault();
				e.stopPropagation();
				openStaffProModal();
			}
		}

		['pointerdown', 'mousedown', 'touchstart', 'click'].forEach(function(evt) {
			staffModal.addEventListener(evt, captureHandler, true);
		});
	})();

 	$('#apbgf-booking_type').on('change', function() {
 		if ( 'fullday' == $(this).val() ) {
 			$('#apbgf-lead-time-container').hide();
 			$('form#apbgf-staff-form-timings .form-start-time-slots, form#apbgf-staff-form-timings .form-end-time-slots, form#apbgf-staff-form-timings #apbgf-duration, form#apbgf-staff-form-timings #apbgf-interval').addClass('form-time-slots-disabled');
 		} else {
 			$('#apbgf-lead-time-container').show();
 			$('#apbgf-staff-form-timings .form-start-time-slots, #apbgf-staff-form-timings .form-end-time-slots, #apbgf-staff-form-timings #apbgf-duration, #apbgf-staff-form-timings #apbgf-interval').removeClass('form-time-slots-disabled');
 		}
 		apbgfSyncStaffTimingsAddBreakState();
 	});

	$(document).on('click', '.apbgf-pro-trigger', function(e) {
		var $target = $(e.target);
		var modalId = $(this).data('apbgf-pro-modal') || 'apbgf-pro-modal';
		var $modal = $(`#${modalId}`);
		if ( $modal.length === 0 ) {
			return;
		}
		// For email PRO accordion headers: allow expand/collapse and also open popup.
		if ( $target.closest('#accordion .ui-accordion-header, #accordion .apbgf_section-title').length > 0 ) {
			$('body').addClass('apbgf-modal-open');
			if ( $modal.hasClass('apbgf-pro-modal') ) {
				$modal.show();
			} else {
				$modal.addClass('apbgf-modal-show');
			}
			return;
		}
		e.preventDefault();
		e.stopPropagation();
		$('body').addClass('apbgf-modal-open');
		if ( $modal.hasClass('apbgf-pro-modal') ) {
			$modal.show();
		} else {
			$modal.addClass('apbgf-modal-show');
		}
	});

 	$('.form-time-slots-content-row .apbgf_staff_time_toggle').on('click', function() {		
 		if ( $(this).is(':checked') ) {
 			$(this).parents('.form-time-slots-content-row').find('.form-slots-capacity').removeClass('form-time-slots-disabled');
 		} else {
 			$(this).parents('.form-time-slots-content-row').find('.form-slots-capacity').addClass('form-time-slots-disabled');
 		}
 	});

	// $(document).on('click', '.remove_spl_date', function(event) {
 	
	// 	$(this).parents('.spl_day_repeater_block').remove();
	// 	var len = $('#spl_day_repeater_wrapper').find('.spl_day_repeater_block').length;

	// 	$('#spl_day_repeater_wrapper > div.spl_day_repeater_block').each(function(i, v) {
	// 		$(this).data('id', i);
	// 	});
	// });

	// $('#add_spl_date').on('click', function(event) {

	// 	event.preventDefault();

	// 	var len = $('#spl_day_repeater_wrapper').find('.spl_day_repeater_block').length;

	// 	if ( len == 0 || 'undefined' == len ) {
	// 		len = 0;
	// 	}

	// 	$('#spl_day_repeater_wrapper').append(`
	// 		<div class="spl_day_repeater_block" data-id="${len}">
	// 			<div class="form-col-full">
    //                 <input type="number" class="apbgf-spl-duration" name="apbgf_staff_spl_day_timing[${len}][duration]" min="1" data-general="${apbgf_admin.time_duration}" value="${apbgf_admin.time_duration}">
    //                 <small>${apbgf_admin.durationHelpTxt}</small>
    //             </div>
    //             <div class="form-col-full">                                
    //                 <input type="number" class="apbgf-spl-interval" name="apbgf_staff_spl_day_timing[${len}][interval]" min="0" data-general="${apbgf_admin.time_interval}" value="${apbgf_admin.time_interval}">
    //                 <small>${apbgf_admin.intervalHelpTxt}</small>
    //             </div>
	//             <div class="form-time-slots-content-row">
	//                 <div class="form-start-time-slots">
	//                     <input type="time" name="apbgf_staff_spl_day_timing[${len}][start]" class="apbgf_staff_spl_event_start" data-id="${len}">
	//                     <small>${apbgf_admin.startTimeLbl}</small>
	//                 </div>
	//                 <div class="form-end-time-slots">
	//                     <input type="time" name="apbgf_staff_spl_day_timing[${len}][end]" class="apbgf_staff_spl_event_end" data-id="${len}">
	//                     <small>${apbgf_admin.endTimeLbl}</small>
	//                 </div>
	//                 <div class="form-end-time-slots">
	//                     <input type="date" name="apbgf_staff_spl_day_timing[${len}][date]" class="apbgf_staff_spl_event_date">
	//                     <small>${apbgf_admin.dateLbl}</small>
	//                 </div>
	//                 <div class="form-slots-capacity">
	//                     <input type="number" name="apbgf_staff_spl_day_timing[${len}][capacity]" class="apbgf_staff_spl_event_capacity" min="1">
	//                     <small>${apbgf_admin.capacityLbl}</small>
	//                 </div>
	//                 <div class="add-break-btn">
	//                 	<span class="remove_spl_date"><i class="fa fa-minus-circle"></i> ${apbgf_admin.removeSlotTxt}</span>
	//                     <span data-id="${len}"><i class="fa fa-plus-circle"></i> ${apbgf_admin.addBreakTxt}</span>
	//                 </div>
	//             </div>
	//             <div id="break-${len}" class="form-time-slots-break-box">
	//                 <div class="form-col-full">
	//                     <label for="add-break">${apbgf_admin.addBreakTxt}</label>
	//                     <select name="apbgf_staff_spl_day_timing[${len}][break][]" id="apbgf_staff_timing_${len}_break" class="apbgf-slot-break" multiple></select>
	//                 </div>
	//             </div>
	//         </div>
	// 	`);

	// 	//initializing staff time slot break select2
	// 	$('.apbgf-slot-break').select2();
	// });

 	$('.apbgf-edit').on('click', function(e) {
 		e.preventDefault();
 		var id = $(this).data('id');
 		var post_id = $(this).data('post_id');
 		var type = $(this).data('type');
 		var action = '';

 		window.scrollTo({top: 0});
 		$('body').addClass('apbgf-modal-open');

		//resetting previous values.
 		if ( $('.modal--form').length > 0 ) {
 			$('.apbgf-response').html('').removeClass('success error');
 			if ( 'location' === type && $('#apbgf-location-form').length ) {
 				$('#apbgf-location-form')[0].reset();
 			} else if ( $('.modal--form').length ) {
 				$('.modal--form')[0].reset();
 			}
 			if ( $('#apbgf-staff-form-details').length > 0 ) {
 				$('#apbgf-staff-form-details')[0].reset();
 			}

 			if ( $('#apbgf-staff-form-services').length > 0 ) {
 				$('#apbgf-staff-form-services')[0].reset();
 			}

 			if ( $('#apbgf-staff-form-timings').length > 0 ) {
 				$('#apbgf-staff-form-timings')[0].reset();
 				apbgfSyncStaffTimingsAddBreakState();
 			}

 			if ( $('#apbgf-staff-form-spl-day').length > 0 ) {
 				$('#apbgf-staff-form-spl-day')[0].reset();
 			}

 			$('input[type=checkbox]').prop('checked', false);
 		}

 		if ( post_id != '' && type != '' && id != '' ) {

 			if ( 'location' == type ) {
 				action = 'apbgf_show_location_data';
 			}

 			if ( 'staff' == type ) {
 				action = 'apbgf_show_staff_data';
 			}

 			if ( 'customer' == type ) {
 				action = 'apbgf_show_customer_data';
 			}

 			if ( 'service' == type ) {
 				action = 'apbgf_show_service_data';
 			}

 			if ( 'appointment' == type ) {
 				action = 'apbgf_show_appointment_data';
 			}

 			$.ajax({
 				url: apbgf_admin.ajaxurl,
 				type: 'POST',
 				data: `post_id=${post_id}&action=${action}&nonce=${apbgf_admin.nonce}`,
 				beforeSend: function() {
 					$('body').append('<div id="apbgf-overlay" />');
 				},
 				success: function (response) {
 					var response = $.parseJSON(response);
 					if ( 'success' == response.status ) {
 						if ( 'location' === type ) {
 							$('#apbgf-location-form .post_id').val( post_id );
 							$('#apbgf-name').val( response.name || '' );
 							$('#apbgf-phone').val( response.phone || '' );
 							$('#apbgf-address').val( response.address || '' );
 							$('#apbgf-description').val( response.description || '' );
 						} else if ( $('.post_id').length > 0 ) {
 							$('.post_id').val(post_id);
 						}
 						
 						if ( 'appointment' != type && 'location' != type ) {
 							$.each( response, function(i, v) {								
								
 								if ( $(`#apbgf-${i}`).length > 0 ) {
 									if ( 'multiple_booking' == i ) {										
 										$('input[name="multiple_booking"]').removeAttr('checked');
 										$(`#apbgf-multiple_booking-${v}`).prop('checked', true);
 									} else if ( 'duration' == i || 'interval' == i ) {
 										$(`#apbgf-${i}`).val(v);
 									} else {
 										$(`#apbgf-${i}`).val(v).trigger('change');
 									}
 								}

								//if action is for staff so we will check for staff services
 								if ( 'services' === i ) {
									
 									$.each( v, function(ii, vv) {
 										if ( $(`#apbgf_staff_service_aval_${ii}`).length > 0 ) {
 											$(`#apbgf_staff_service_aval_${ii}`).prop('checked', true);
 											$(`#apbgf_staff_service_price_${ii}`).val(vv.price);
 										}
 									});
 								}
 								
								//if action is for staff so we will check for staff services
 								if ( 'timings' === i ) {
 									$('#apbgf-booking_type').trigger('change');
 									$('#apbgf-lead-time').val( response.lead_time );
 									$.each( v, function(ii, vv) {								
 										if ( $(`#apbgf_staff_timing_${ii}_start`).length > 0 ) {
 											if ( '1' == vv.switch ) {
 												$(`#apbgf_staff_timing_${ii}_switch`).prop('checked', true);
 											}											
											$(`#apbgf_staff_timing_${ii}_start`).val( apbgfFormatTimeForInput( vv.start ) );
											$(`#apbgf_staff_timing_${ii}_end`).val( apbgfFormatTimeForInput( vv.end ) );
 											$(`#apbgf_staff_timing_${ii}_capacity`).val(vv.capacity);

											// $.each( vv.break, function( iii, vvv ) {
											// 	$(`#apbgf_staff_timing_${ii}_break`).val(vv.capacity);
											// });										
 										}
 									});
 								}

 								if ( 'time_slots' === i ) {
 									
 									if ( $(`#apbgf-staff-form-timings .apbgf-slot-break`).length > 0 ) {
 										$(`#apbgf-staff-form-timings .apbgf-slot-break`).html('');
 									}

 									$.each( v, function(ii, vv) {
 										if ( $(`#apbgf_staff_timing_${ii}_break`).length > 0 ) {											
 											$.each( vv.slot, function( xx, yy ) {												
 												var selected = false;
 												if ( $.inArray(vv.start[xx], response.timings[ii].break) >= 0 ) {
 													var selected = true;
 												}
 												
												

 												$(`#apbgf_staff_timing_${ii}_break`).append($('<option>', {												
 													value: vv.start[xx],
 													text: yy,
 													selected: selected
 												}));												
 											});
 										}
 									});
 									apbgfSyncStaffTimingsAddBreakState();
 								}

								//if action is for staff so we will check for staff spl day timings
 								if ( 'spl_day_timings' === i ) {
									
									//empty before adding looping block
 									$('#spl_day_repeater_wrapper').html('');
 									var spl_time_slots = response.spl_day_time_slots;
 									
 									$.each( v, function(ii, vv) {
 										
 										if ( typeof vv.date != 'undefined' ) {
 											var date = new Date(vv.date);
 											var dayName = date.toLocaleString('en-US', { weekday: 'short' }).toLowerCase();
											
											var spl_day_time_slots = spl_time_slots[vv.date][dayName];
											

											$('#spl_day_repeater_wrapper').append(`
												<div class="spl_day_repeater_block" data-id="${ii}">
													<div class="form-col-full">
									                    <input type="number" class="apbgf-spl-duration" name="apbgf_staff_spl_day_timing[${ii}][duration]" min="1" data-general="${apbgf_admin.time_duration}" placeholder="${apbgf_admin.time_duration}" value="${vv.duration}">
									                    <small>${apbgf_admin.durationHelpTxt}</small>
									                </div>
									                <div class="form-col-full">                                
									                    <input type="number" class="apbgf-spl-interval" name="apbgf_staff_spl_day_timing[${ii}][interval]" min="0" data-general="${apbgf_admin.time_interval}" placeholder="${apbgf_admin.time_interval}" value="${vv.interval}">
									                    <small>${apbgf_admin.intervalHelpTxt}</small>
									                </div>   
		                                            <div class="form-time-slots-content-row">   
		                                                <div class="form-start-time-slots">
		                                                    <input type="time" name="apbgf_staff_spl_day_timing[${ii}][start]" class="apbgf_staff_spl_event_start" data-id="${ii}" value="${vv.start}">
		                                                    <small>${apbgf_admin.startTimeLbl}</small>
		                                                </div>
		                                                <div class="form-end-time-slots">
		                                                    <input type="time" name="apbgf_staff_spl_day_timing[${ii}][end]" class="apbgf_staff_spl_event_end" data-id="${ii}" value="${vv.end}">
		                                                    <small>${apbgf_admin.endTimeLbl}</small>
		                                                </div>
		                                                <div class="form-end-time-slots">
		                                                    <input type="date" name="apbgf_staff_spl_day_timing[${ii}][date]" class="apbgf_staff_spl_event_date" value="${vv.date}">
		                                                    <small>${apbgf_admin.dateLbl}</small>
		                                                </div>
		                                                <div class="form-slots-capacity">
		                                                    <input type="number" name="apbgf_staff_spl_day_timing[${ii}][capacity]" class="apbgf_staff_spl_event_capacity" min="1" value="${vv.capacity}">
		                                                    <small>${apbgf_admin.capacityLbl}</small>
		                                                </div>
		                                                <div class="add-break-btn">
		                                                	<span class="remove_spl_date"><i class="fa fa-minus-circle"></i> ${apbgf_admin.removeSlotTxt}</span>
		                                                    <span data-id="${ii}"><i class="fa fa-plus-circle"></i> ${apbgf_admin.addBreakTxt}</span>
		                                                </div>
		                                            </div>
		                                            <div id="break-${ii}" class="form-time-slots-break-box">
		                                                <div class="form-col-full" id="selectBreakWrapper_${ii}">
		                                                    <label for="add-break">${apbgf_admin.addBreakTxt}</label>
		                                                    <select name="apbgf_staff_spl_day_timing[${ii}][break][]" id="apbgf_staff_timing_${ii}_break" class="apbgf-slot-break" multiple></select>
		                                                </div>
		                                            </div>
		                                        </div>
											`);

											$.each(spl_day_time_slots.slot, function(index, slot) {	

												var selected = false;
	                                    		
												if ( $.inArray(spl_day_time_slots.start[index], response.spl_day_timings[ii].break) >= 0 ) {
													var selected = true;
												}
												
												$(`#apbgf_staff_timing_${ii}_break`).append($('<option>', {
													value: spl_day_time_slots.start[index],
													text:  slot,
													selected: selected
												}));
											});

											//initializing staff time slot break select2
											$(`#apbgf_staff_timing_${ii}_break`).select2();
										}
									});
}

if ( 'holidays' === i ) {
	dateRanges = v;
	if ( $(datePickerAddHolidayField).length > 0 ) {
		if ( apbgfIsFirefox() ) {
			if ( $( '#add_holidays' ).hasClass( 'apbgf-tab-active' ) ) {
				apbgfInitStaffHolidayPicker( 'add' );
			}
			if ( $( '#remove_holidays' ).hasClass( 'apbgf-tab-active' ) ) {
				apbgfInitStaffHolidayPicker( 'remove' );
			}
		} else {
			apbgfInitStaffHolidayPicker( 'both' );
		}
	}
}
});
						} else { //only for appointment type
							
							$.each( response, function(i, v) {
								if ( 'status' !== i  ) {
									$(`#${i}`).html(v);
								}
							});
						}

						if ( 'staff' === type ) {
							apbgfRefreshStaffTimeInputs( '#apbgf-staff-form-timings' );
							apbgfRefreshStaffTimeInputs( '#spl_day_repeater_wrapper' );
							apbgfSyncStaffTimingsAddBreakState();
						}

						//modal to open
						$(`#${id}`).addClass('apbgf-modal-show');

					} else {
						swalWithBootstrapButtons.fire(
							'No User Found!',
							'',
							response.status
							);
					}
				},
				complete: function() {
					$('#apbgf-overlay').remove();
				}
			});
}
});

 $('.apbgf-delete').on( 'click', function( event ) {
 	event.preventDefault();
 	var type = $(this).data('type');
 	var post_id = $(this).data('post_id');
 	var action = '';

 	if ( 'location' == type ) {
 		action = 'apbgf_delete_location';
 	}

 	if ( 'staff' == type ) {
 		action = 'apbgf_delete_staff';
 	}

 	if ( 'customer' == type ) {
 		action = 'apbgf_delete_customer';
 	}

 	if ( 'service' == type ) {
 		action = 'apbgf_delete_service';
 	}

 	if ( 'appointment' == type ) {
 		action = 'apbgf_delete_appointment';
 	}

 	swalWithBootstrapButtons.fire({
 		title: 'Are you sure?',
 		text: "You won't be able to revert this!",
 		icon: 'warning',
 		showCancelButton: true,
 		confirmButtonText: 'Yes, delete it!',
 		cancelButtonText: 'No, cancel!',
 		reverseButtons: true
 	}).then((result) => {
 		if (result.isConfirmed) {
 			$.ajax({
 				url: apbgf_admin.ajaxurl,
 				type: 'POST',
 				data: `post_id=${post_id}&action=${action}&nonce=${apbgf_admin.nonce}`,
 				beforeSend: function() {
 					$('body').append('<div id="apbgf-overlay" />');
 				},
 				success: function (response) {
 					var response = $.parseJSON(response);
 					if ( 'success' == response.status ) {
 						swalWithBootstrapButtons.fire(
 							'Deleted!',
 							response.message,
 							response.status
 							).then((result) => {
 								location.reload();
 							});
 						} else {
 							swalWithBootstrapButtons.fire(
 								'Not deleted!',
 								response.message,
 								response.status
 								);
 						}
 					},
 					complete: function() {
 						$('#apbgf-overlay').remove();
 					}
 				});
 		} else if (result.dismiss === Swal.DismissReason.cancel) {
 			swalWithBootstrapButtons.fire(
 				'Cancelled',
 				'',
 				'error'
 				)
 		}
 	});

 });

 $('.apbgf-appointment-status').on( 'change', function( event ) {
 	event.preventDefault();		
 	var post_id = $(this).data('post_id');
 	var status = $(this).val();
 	var action = 'apbgf_change_appointment_status';

 	if ( ''!== post_id ) {
 		swalWithBootstrapButtons.fire({
 			title: 'Are you sure?',
 			text: "You want to change the appointment status",
 			icon: 'warning',
 			showCancelButton: true,
 			confirmButtonText: 'Yes, Change it!',
 			cancelButtonText: 'No, cancel!',
 			reverseButtons: true
 		}).then((result) => {
 			if (result.isConfirmed) {
 				$.ajax({
 					url: apbgf_admin.ajaxurl,
 					type: 'POST',
 					data: `post_id=${post_id}&status=${status}&action=${action}&nonce=${apbgf_admin.nonce}`,
 					beforeSend: function() {
 						$('body').append('<div id="apbgf-overlay" />');
 					},
 					success: function (response) {
 						var response = $.parseJSON(response);
 						if ( 'success' == response.status ) {
 							swalWithBootstrapButtons.fire(
 								'Changed!',
 								response.message,
 								response.status
 								).then((result) => {
 									location.reload();
 								});
 							} else {
 								swalWithBootstrapButtons.fire(
 									'Not Changed!',
 									response.message,
 									response.status
 									);
 							}
 						},
 						complete: function() {
 							$('#apbgf-overlay').remove();
 						}
 					});
 			} else if (result.dismiss === Swal.DismissReason.cancel) {
 				swalWithBootstrapButtons.fire(
 					'Cancelled',
 					'',
 					'error'
 					)
 			}
 		});
 	}	
 });

 $('.apbgf_show_reason').on('click', function(e) {
 	e.preventDefault();
 	var reason = $(this).data('reason');
 	if ( $.trim( reason ) != '' ) {
 		swalWithBootstrapButtons.fire(
 			'Reason of cancellation',
 			reason	      		
 			);
 	}
 });

	// MODAIL FORM TABS SCRIPTS
 var generate_tabs = function( callback ) {
 	'use strict';
		/*Activate default tab contents*/
 	var leftPos, newWidth, $magicLine, defaultActive, $staffTabs;

 	$staffTabs = $( '#apbgf-staff-modal .staff_tabs' );
 	if ( $staffTabs.length === 0 ) {
 		$staffTabs = $( '.staff_tabs' ).first();
 	}

 	defaultActive = $staffTabs.find( '.tabs li.active a' ).attr( 'href' );

 	$('.staff_tabs .tabs').append("<li id='magic-line'></li>");
 	$magicLine = $('.staff_tabs #magic-line');
 	if ( $magicLine.length > 0 ) {
 		$magicLine.width($('.staff_tabs .active').width())
 		.css('left', $('.staff_tabs .active a').position().left)
 		.data('origLeft', $magicLine.position().left)
 		.data('origWidth', $magicLine.width());
 	}

 	function updateMagicLine( $tabLink ) {
 		$magicLine
 			.stop()
 			.animate( {
 				left: $tabLink.position().left,
 				width: $tabLink.parent().width()
 			} )
 			.data( 'origLeft', $tabLink.position().left )
 			.data( 'origWidth', $tabLink.parent().width() );
 	}

 	if ( apbgfIsFirefox() ) {
 		$staffTabs.addClass( 'apbgf-staff-tabs--firefox' );
 		$staffTabs.find( '.tabContent' ).removeClass( 'apbgf-tab-active' );
 		$staffTabs.find( defaultActive ).addClass( 'apbgf-tab-active' );
 		$staffTabs.find( '.tabWrapper' ).css( 'left', 0 );
 	} else {
 		$( defaultActive ).show();
 	}

 	$staffTabs.find( '.tabs li a' ).off( 'click.apbgfStaffTabs' ).on( 'click.apbgfStaffTabs', function() {
 		var $this, tabId, leftVal, $tabContent;
 		$this = $( this );
 		$tabContent = $staffTabs.find( '.tabContent' );
 		$this.parent().addClass( 'active' ).siblings().removeClass( 'active' );
 		tabId = $this.attr( 'href' );

 		if ( apbgfIsFirefox() ) {
 			$tabContent.removeClass( 'apbgf-tab-active' );
 			$staffTabs.find( tabId ).addClass( 'apbgf-tab-active' );
 			$staffTabs.find( '.tabWrapper' ).css( 'left', 0 );
 			updateMagicLine( $this );
 			callback( $this );
 			return false;
 		}

 		leftVal = $tabContent.index( $staffTabs.find( tabId ) ) * $tabContent.width() * -1;
 		$staffTabs.find( '.tabWrapper' ).stop().animate( { left: leftVal }, function() {
 			callback( $this );
 		} );

 		updateMagicLine( $this );

 		return false;
 	} );

		/*Magicline hover animation*/
 	$('.staff_tabs .tabs li').find('a').hover(function() {
 		var $thisBar = $(this);
 		leftPos = $thisBar.position().left;
 		newWidth = $thisBar.parent().width();
 		$magicLine.stop().animate({left:leftPos,width:newWidth});
 	}, function() {
 		$magicLine.stop().animate({left:$magicLine.data('origLeft'),width: $magicLine.data('origWidth')});
 	});
 }

 generate_tabs(function( $this) {
		var tabHref = $this.attr( 'href' );
		var tabDelay = apbgfIsFirefox() ? 50 : 450;

		if ( '#timings' === tabHref ) {
			setTimeout( function() {
				apbgfSyncStaffTimingsAddBreakState();
				apbgfRefreshStaffTimeInputs( '#apbgf-staff-form-timings' );
			}, tabDelay );
		}

		if ( '#spl_day' === tabHref ) {
			setTimeout( function() {
				apbgfRefreshStaffTimeInputs( '#spl_day_repeater_wrapper' );
			}, tabDelay );
		}

		if ( apbgfIsFirefox() && '#add_holidays' === tabHref ) {
			setTimeout( function() {
				apbgfInitStaffHolidayPicker( 'add' );
			}, tabDelay );
		}

		if ( apbgfIsFirefox() && '#remove_holidays' === tabHref ) {
			setTimeout( function() {
				apbgfInitStaffHolidayPicker( 'remove' );
			}, tabDelay );
		}
 });

	//Import customers via ajax
 $('#apbgf-customer-import-form').on( 'submit', function( event ) {

 	event.preventDefault();		
 	var action = 'apbgf_customer_import';
 	var file = $('#apbgf-file')[0].files[0];
 	var formData = new FormData();
 	formData.append('action', action);
 	formData.append('nonce', apbgf_admin.nonce);
 	formData.append('csv_file', file);

 	if (file.type !== 'text/csv') {
 		$('#apbgf-customer-import-form').find('.apbgf-response').addClass('error');
 		$('#apbgf-customer-import-form').find('.apbgf-response').html('Invalid file type. Please select a CSV file.');
 		return;
 	}

 	if (file.size > 2000000) {
 		$('#apbgf-customer-import-form').find('.apbgf-response').addClass('error');
 		$('#apbgf-customer-import-form').find('.apbgf-response').html('File size exceeds the maximum limit of 2MB.');            
 		return;
 	}

 	$.ajax({
 		url: apbgf_admin.ajaxurl,
 		type: 'POST',
 		data: formData,
 		contentType: false,
 		processData: false,
 		beforeSend: function () {
 			$('#apbgf-customer-import-form').append('<div class="apbgf-modal-overlay" />');
 			$('#apbgf-customer-import-form').find('.apbgf-response').html('');
 			$('.apbgf-response').removeClass('error').removeClass('success');
 		},
 		success: function (response) {
 			var response = $.parseJSON(response);
				
 			$('#apbgf-customer-import-form').find('.apbgf-response').addClass(response.status);
 			$('#apbgf-customer-import-form').find('.apbgf-response').html(response.message);
 			if ( 'success' == response.status ) {
 				
 			}
 		},
 		complete: function () {
 			$('.apbgf-modal-overlay').remove();
 		}
 	});
 });

	//add Customer ajax
 $('#apbgf-customer-form').validate({
 	rules: {
		    // simple rule, converted to {required:true}
 		fname: {
 			required: true
 		},
 		lname: {
 			required: true
 		},
 		field: {
 			required: true,
 			email: true
 		},	    
 	},
 	highlight: function(element, errorClass) {			
 		$(element).addClass('errorBorder');	
 	},
 	success: function (label, element) {
 		$(element).removeClass('errorBorder');
 	},
 	submitHandler: function( form ) {
 		var This = $(form);
 		var post_id = '';
 		var action = '';

 		if ( $(This).find('.post_id').length > 0 ) {
 			post_id = $(This).find('.post_id').val();
 		}

 		if ( post_id != '' ) {
 			action = 'apbgf_edit_customer';
 		} else {
 			action = 'apbgf_add_customer';
 		}

 		var formData = $(This).serialize() + `&action=${action}&nonce=${apbgf_admin.nonce}`;
 		$.ajax({
 			url: apbgf_admin.ajaxurl,
 			type: 'POST',
 			data: formData,
 			beforeSend: function () {
 				$('#apbgf-customer-form').find('.errorBorder').removeClass('errorBorder');
 				$('#apbgf-customer-form').append('<div class="apbgf-modal-overlay" />');
 				$('#apbgf-customer-form').find('.apbgf-response').html('');
 				$('.apbgf-response').removeClass('error').removeClass('success');
 			},
 			success: function (response) {
 				var response = $.parseJSON(response);
					
 				$('#apbgf-customer-form').find('.apbgf-response').addClass(response.status);
 				$('#apbgf-customer-form').find('.apbgf-response').html(response.message);
				if ( 'success' == response.status ) {
					setTimeout( function () {
						$('#apbgf-customer-modal').removeClass('apbgf-modal-show');
						$('body').removeClass('apbgf-modal-open');
						location.reload();
					}, 1200 );
				}
 			},
 			complete: function () {
 				$('.apbgf-modal-overlay').remove();
 			}
 		});
 	}

 });

	//add Staff Details ajax
 $('#apbgf-staff-form-details').validate({
 	rules: {
		    // simple rule, converted to {required:true}
 		fname: {
 			required: true
 		},
 		lname: {
 			required: true
 		},
 		field: {
 			required: true,
 			email: true
 		},	    
 	},
 	highlight: function(element, errorClass) {			
 		$(element).addClass('errorBorder');	
 	},
 	success: function (label, element) {
 		$(element).removeClass('errorBorder');
 	},
 	submitHandler: function( form ) {
 		var This = $(form);
 		var post_id = '';
 		var action = '';

 		if ( $(This).find('.post_id').length > 0 ) {
 			post_id = $(This).find('.post_id').val();
 		}

 		if ( post_id != '' ) {
 			action = 'apbgf_edit_staff';
 		} else {
 			action = 'apbgf_add_staff';
 		}

 		var formData = $(This).serialize() + `&action=${action}&nonce=${apbgf_admin.nonce}`;
 		$.ajax({
 			url: apbgf_admin.ajaxurl,
 			type: 'POST',
 			data: formData,
 			beforeSend: function () {
 				$('#apbgf-staff-form-details').find('.errorBorder').removeClass('errorBorder');
 				$('#apbgf-staff-form-details').append('<div class="apbgf-modal-overlay" />');
 				$('#apbgf-staff-form-details').find('.apbgf-response').html('');
 				$('.apbgf-response').removeClass('error').removeClass('success');
 			},
 			success: function (response) {
 				var response = $.parseJSON(response);
				
 				$('#apbgf-staff-form-details').find('.apbgf-response').addClass(response.status);
 				$('#apbgf-staff-form-details').find('.apbgf-response').html(response.message);
 				if ( 'success' == response.status ) {
 					$('#apbgf-staff-form-details')[0].reset();
 					location.reload();
 				}
 			},
 			complete: function () {
 				$('.apbgf-modal-overlay').remove();
 			}
 		});
 	}
 });

	/*$('#apbgf-staff-form-details').on( 'submit', function( event ) {

		event.preventDefault();
		var post_id = '';
		var action = '';

		if ( $(this).find('.post_id').length > 0 ) {
			post_id = $(this).find('.post_id').val();
		}

		if ( post_id != '' ) {
			action = 'apbgf_edit_staff';
		} else {
			action = 'apbgf_add_staff';
		}

		var formData = $(this).serialize() + `&action=${action}&nonce=${apbgf_admin.nonce}`;
		$.ajax({
			url: apbgf_admin.ajaxurl,
			type: 'POST',
			data: formData,
			beforeSend: function () {
				$('#apbgf-staff-form-details').append('<div class="apbgf-modal-overlay" />');
				$('#apbgf-staff-form-details').find('.apbgf-response').html('');
				$('.apbgf-response').removeClass('error').removeClass('success');
			},
			success: function (response) {
				var response = $.parseJSON(response);
				
				$('#apbgf-staff-form-details').find('.apbgf-response').addClass(response.status);
				$('#apbgf-staff-form-details').find('.apbgf-response').html(response.message);
				if ( 'success' == response.status ) {
					$('#apbgf-staff-form-details')[0].reset();
					location.reload();
				}
			},
			complete: function () {
				$('.apbgf-modal-overlay').remove();
			}
		});
	});*/


	//add Staff Services ajax
 $('#apbgf-staff-form-services').on( 'submit', function( event ) {

 	event.preventDefault();
 	var post_id = '';
 	var action = 'apbgf_add_staff_services';

 	if ( $(this).find('.post_id').length > 0 ) {
 		post_id = $(this).find('.post_id').val();
 	}		

 	var formData = $(this).serialize() + `&action=${action}&nonce=${apbgf_admin.nonce}`;
 	$.ajax({
 		url: apbgf_admin.ajaxurl,
 		type: 'POST',
 		data: formData,
 		beforeSend: function () {
 			$('#apbgf-staff-form-services').append('<div class="apbgf-modal-overlay" />');
 			$('#apbgf-staff-form-services').find('.apbgf-response').html('');
 			$('.apbgf-response').removeClass('error').removeClass('success');
 		},
 		success: function (response) {
 			var response = $.parseJSON(response);
				
 			$('#apbgf-staff-form-services').find('.apbgf-response').addClass(response.status);
 			$('#apbgf-staff-form-services').find('.apbgf-response').html(response.message);
 			if ( 'success' == response.status ) {
					//$('#apbgf-staff-form-services')[0].reset();
					//location.reload();
 			}
 		},
 		complete: function () {
 			$('.apbgf-modal-overlay').remove();
 		}
 	});
 });


	//add Staff Timings ajax
 $('#apbgf-staff-form-timings').on( 'submit', function( event ) {


	event.preventDefault();
	var $form = $(this);
	var bookingType = $('#apbgf-booking_type').val();
	var showError = false;
	var errorFields = [];

	// Only validate timing fields if not 'fullday'
	if (bookingType !== 'fullday') {
		// Validate start/end time, duration, interval, capacity fields
		$form.find('.form-start-time-slots input, .form-end-time-slots input, #apbgf-duration, #apbgf-interval, .form-slots-capacity input').each(function() {
			if (!$(this).hasClass('form-time-slots-disabled') && $(this).is(':visible')) {
				if ($(this).prop('required') && !$(this).val()) {
					showError = true;
					errorFields.push(this);
				}
			}
		});
	}

	// Show error if needed
	$form.find('.errorBorder').removeClass('errorBorder');
	if (showError) {
		$(errorFields).addClass('errorBorder');
		$form.find('.apbgf-response').addClass('error').html('Please fill all required timing fields.');
		return;
	}

	var post_id = '';
	var action = 'apbgf_add_staff_timings';
	if ($form.find('.post_id').length > 0) {
		post_id = $form.find('.post_id').val();
	}
	var formData = $form.serialize() + `&action=${action}&nonce=${apbgf_admin.nonce}`;
	$.ajax({
		url: apbgf_admin.ajaxurl,
		type: 'POST',
		data: formData,
		beforeSend: function () {
			$('#apbgf-staff-form-timings').append('<div class="apbgf-modal-overlay" />');
			$('#apbgf-staff-form-timings').find('.apbgf-response').html('');
			$('.apbgf-response').removeClass('error').removeClass('success');
		},
		success: function (response) {
			var response = $.parseJSON(response);
			$('#apbgf-staff-form-timings').find('.apbgf-response').addClass(response.status);
			$('#apbgf-staff-form-timings').find('.apbgf-response').html(response.message);
			if ('success' == response.status) {
				//$('#apbgf-staff-form-timings')[0].reset();
				//location.reload();
			}
		},
		complete: function () {
			$('.apbgf-modal-overlay').remove();
		}
	});
});

	//add Staff Spl Timings ajax
	// $('#apbgf-staff-form-spl-day').on( 'submit', function( event ) {

	// 	event.preventDefault();
	// 	var post_id = '';
	// 	var action = 'apbgf_add_staff_spl_timings';

	// 	if ( $(this).find('.post_id').length > 0 ) {
	// 		post_id = $(this).find('.post_id').val();
	// 	}		

	// 	var formData = $(this).serialize() + `&action=${action}&nonce=${apbgf_admin.nonce}`;


 
	// 	$.ajax({
	// 		url: apbgf_admin.ajaxurl,
	// 		type: 'POST',
	// 		data: formData,
	// 		beforeSend: function () {
	// 			$('#apbgf-staff-form-spl-day').append('<div class="apbgf-modal-overlay" />');
	// 			$('#apbgf-staff-form-spl-day').find('.apbgf-response').html('');
	// 			$('.apbgf-response').removeClass('error').removeClass('success');
	// 		},
	// 		success: function (response) {
	// 			var response = $.parseJSON(response);
	// 			
	// 			$('#apbgf-staff-form-spl-day').find('.apbgf-response').addClass(response.status);
	// 			$('#apbgf-staff-form-spl-day').find('.apbgf-response').html(response.message);
	// 			if ( 'success' == response.status ) {
	// 				//$('#apbgf-staff-form-spl-day')[0].reset();
	// 				//location.reload();
	// 			}
	// 		},
	// 		complete: function () {
	// 			$('.apbgf-modal-overlay').remove();
	// 		}
	// 	});
	// });

 

 	//add Location ajax
 	$('#apbgf-location-form').on( 'submit', function( event ) {

 		event.preventDefault();
 		var This = $(this);
 		var post_id = '';
 		var action = '';

 		if ( $(This).find('.post_id').length > 0 ) {
 			post_id = $(This).find('.post_id').val();
 		}

 		if ( post_id != '' ) {
 			action = 'apbgf_edit_location';
 		} else {
 			action = 'apbgf_add_location';
 		}

 		var formData = $(This).serialize() + `&action=${action}&nonce=${apbgf_admin.nonce}`;
 		$.ajax({
 			url: apbgf_admin.ajaxurl,
 			type: 'POST',
 			data: formData,
 			beforeSend: function () {
 				$('#apbgf-location-form').find('.errorBorder').removeClass('errorBorder');
 				$('#apbgf-location-form').append('<div class="apbgf-modal-overlay" />');
 				$('#apbgf-location-form').find('.apbgf-response').html('');
 				$('.apbgf-response').removeClass('error').removeClass('success');
 			},
 			success: function (response) {
 				var parsed = $.parseJSON( response );
 				$('#apbgf-location-form').find('.apbgf-response').addClass( parsed.status );
 				$('#apbgf-location-form').find('.apbgf-response').html( parsed.message );
 				if ( 'success' === parsed.status ) {
 					var savedId = parsed.post_id || post_id;
 					if ( savedId ) {
 						$('#apbgf-location-form .post_id').val( savedId );
 					}
 					$('#apbgf-name').val( parsed.name || $('#apbgf-name').val() );
 					$('#apbgf-phone').val( parsed.phone || '' );
 					$('#apbgf-address').val( parsed.address || '' );
 					$('#apbgf-description').val( parsed.description || '' );
 					$('#apbgf-location-modal').removeClass( 'apbgf-modal-show' );
 					$('body').removeClass( 'apbgf-modal-open' );
 					window.location.reload();
 				}
 			},
 			complete: function () {
 				$('.apbgf-modal-overlay').remove();
 			}
 		});
 	});

	//add Service ajax
 $('#apbgf-service-form').validate({
 	rules: {
		    // simple rule, converted to {required:true}
 		name: {
 			required: true		    	
 		},
 		category: {
 			required: true		    	
 		},		    
 	},
 	highlight: function(element, errorClass) {
 		$(element).addClass('errorBorder');		
 	},
 	success: function (label, element) {
 		$(element).removeClass('errorBorder');
 	},
 	submitHandler: function( form ) {
 		var This = $(form);
 		var post_id = '';
 		var action = '';

 		if ( $(This).find('.post_id').length > 0 ) {
 			post_id = $(This).find('.post_id').val();
 		}

 		if ( post_id != '' ) {
 			action = 'apbgf_edit_service';
 		} else {
 			action = 'apbgf_add_service';
 		}

 		var formData = $(This).serialize() + `&action=${action}&nonce=${apbgf_admin.nonce}`;
 		$.ajax({
 			url: apbgf_admin.ajaxurl,
 			type: 'POST',
 			data: formData,
 			beforeSend: function () {
 				$('#apbgf-service-form').find('.errorBorder').removeClass('errorBorder');
 				$('#apbgf-service-form').append('<div class="apbgf-modal-overlay" />');
 				$('#apbgf-service-form').find('.apbgf-response').html('');
 				$('.apbgf-response').removeClass('error').removeClass('success');
 			},
 			success: function (response) {
 				var response = $.parseJSON(response);
					
 				$('#apbgf-service-form').find('.apbgf-response').addClass(response.status);
 				$('#apbgf-service-form').find('.apbgf-response').html(response.message);
 				if ( 'success' == response.status ) {
 					$('#apbgf-service-form')[0].reset();
 					location.reload();
 				}
 			},
 			complete: function () {
 				$('.apbgf-modal-overlay').remove();
 			}
 		});
 	}
 });
	// GB free version
 $('#apbgf_label_location').on('input', function() {
 	
 	if ($(this).val().length > 0) {
 		$('.gf_booking_apointments_listing').css('disabled', false);
 		$('.apbgf-booking-pro-version').show();

 	}
 	
 	

 })

 $('.apbgf-pro-cross').on('click', function(event) {

 	event.preventDefault();
 	$('.apbgf-booking-pro-version').hide();
 })
	// ================= / GB free version/ =======================
	//General settings
 $('.apbgf_setting_form').on('submit', function(event) {
 	event.preventDefault();

 	var action = 'apbgf_general_settings';		

 	var formData = $(this).serialize() + `&action=${action}&nonce=${apbgf_admin.nonce}`;
 	$.ajax({
 		url: apbgf_admin.ajaxurl,
 		type: 'POST',
 		data: formData,
 		beforeSend: function() {
 			$('body').append('<div id="apbgf-overlay" />');
				// $('.gf_booking_sidebar').removeClass('.activesidebar');
				// $('.gf_booking_overlayDiv').removeClass('.active');
 		},
 		success: function (response) {
 			var response = $.parseJSON(response);
				
 			swalWithBootstrapButtons.fire(
 				response.status,
 				response.message,
 				response.status
 				);
 		},
 		complete: function() {
 			$('#apbgf-overlay').remove();
 		}
 	});
 });

 $.each( days, function( k, day ) {
 	$(document).on('change', `#apbgf_staff_timing_${day}_start`, function(e) {
 		var time_slots = new Array();
 		let start_time = parseTime($(`#apbgf_staff_timing_${day}_start`).val()),
 		end_time = parseTime($(`#apbgf_staff_timing_${day}_end`).val()),
 		duration = $('#apbgf-duration').val(),
 		interval = $('#apbgf-interval').val();

 		if ( duration == '' ) {
 			duration = $('#apbgf-duration').data('general');
 		}

 		if ( interval == '' ) {
 			interval = $('#apbgf-interval').data('general');
 		}

 		if ( start_time != '' && end_time != '' && start_time < end_time && interval != '' && duration != '' ) {
 			time_slots = apbgf_split_time(start_time, end_time, duration, interval);
 		}

 		$(`#apbgf_staff_timing_${day}_break`).html('');

 		$.each( time_slots, function( i, v ) {											
 			$(`#apbgf_staff_timing_${day}_break`).append($('<option>', {
 				value: v,
 				text: v				
 			}));
 		});
 	});


 	$(document).on('change', `#apbgf_staff_timing_${day}_end`, function(e) {
 		var time_slots = new Array();
 		let start_time = parseTime($(`#apbgf_staff_timing_${day}_start`).val()),
 		end_time = parseTime($(`#apbgf_staff_timing_${day}_end`).val()),
 		duration = $('#apbgf-duration').val(),
 		interval = $('#apbgf-interval').val();

 		if ( duration == '' ) {
 			duration = $('#apbgf-duration').data('general');
 		}

 		if ( interval == '' ) {
 			interval = $('#apbgf-interval').data('general');
 		}

 		if ( start_time != '' && end_time != '' && start_time < end_time && interval != '' && duration != '' ) {
 			time_slots = apbgf_split_time(start_time, end_time, duration, interval);
 		}

 		$(`#apbgf_staff_timing_${day}_break`).html('');

 		$.each( time_slots, function( i, v ) {
 			var val = v.split('-');
 			val = $.trim(val[0]);								
 			$(`#apbgf_staff_timing_${day}_break`).append($('<option>', {
 				value: val,
 				text: v				
 			}));
 		});
 	});

 });

 $('#apbgf-duration, #apbgf-interval').on('keyup copy paste change', function() {
		
 	$('.form-start-time-slots input[type="time"]').trigger('change');
 	$('.form-end-time-slots input[type="time"]').trigger('change');
 });

	/* Special Day start time & end time change create slots */
 $(document).on('change', `.apbgf_staff_spl_event_start`, function(e) {
 	var time_slots = new Array();
 	let start_time = parseTime($(this).val()),
 	id       = $(this).data('id'),
 	end_time = parseTime($(this).parent().siblings('.form-end-time-slots').find('.apbgf_staff_spl_event_end').val()),
 	duration = $(this).parents('.spl_day_repeater_block').find('.apbgf-spl-duration').val(),
 	interval = $(this).parents('.spl_day_repeater_block').find('.apbgf-spl-interval').val();

 	if ( duration == '' ) {
 		duration = $(this).parents('.spl_day_repeater_block').find('.apbgf-spl-duration').data('general');
 	}

 	if ( interval == '' ) {
 		interval = $(this).parents('.spl_day_repeater_block').find('.apbgf-spl-interval').data('general');
 	}

 	if ( start_time != '' && end_time != '' && start_time < end_time && interval != '' && duration != '' ) {
 		time_slots = apbgf_split_time(start_time, end_time, duration, interval);
 	}

 	$(`#apbgf_staff_timing_${id}_break`).html('');

 	$.each( time_slots, function( i, v ) {											
 		$(`#apbgf_staff_timing_${id}_break`).append($('<option>', {
 			value: v,
 			text: v
 		}));
 	});
 });

 $(document).on('change', `.apbgf_staff_spl_event_end`, function(e) {
 	var time_slots = new Array();
 	let start_time = parseTime($(this).parent().siblings('.form-start-time-slots').find('.apbgf_staff_spl_event_start').val()),
 	id       = $(this).data('id'),
 	end_time = parseTime($(this).val()),
 	duration = $(this).parents('.spl_day_repeater_block').find('.apbgf-spl-duration').val(),
 	interval = $(this).parents('.spl_day_repeater_block').find('.apbgf-spl-interval').val();

 	if ( duration == '' ) {
 		duration = $(this).parents('.spl_day_repeater_block').find('.apbgf-spl-duration').data('general');
 	}

 	if ( interval == '' ) {
 		interval = $(this).parents('.spl_day_repeater_block').find('.apbgf-spl-interval').data('general');
 	}

 	if ( start_time != '' && end_time != '' && start_time < end_time && interval != '' && duration != '' ) {
 		time_slots = apbgf_split_time(start_time, end_time, duration, interval);
 	}

 	$(`#apbgf_staff_timing_${id}_break`).html('');

 	$.each( time_slots, function( i, v ) {											
 		$(`#apbgf_staff_timing_${id}_break`).append($('<option>', {
 			value: v,
 			text: v
 		}));
 	});
 });

 $('.apbgf-spl-duration, .apbgf-spl-interval').on('keyup copy paste change', function() {		
 	$(this).parents('.spl_day_repeater_block').find('.apbgf_staff_spl_event_start').trigger('change');
 	$(this).parents('.spl_day_repeater_block').find('.apbgf_staff_spl_event_end').trigger('change');
 });
});

 function getDatesInRange(startDate, endDate) {
 	
 	const dates = [];

 	startDate = new Date(startDate);
 	endDate = new Date(endDate);

 	if ( jQuery.trim(startDate) == '' || jQuery.trim(endDate) == '' ) {
 		return dates;
 	}

 	const date = new Date(startDate.getTime());	

 	while (date <= endDate) {
 		dates.push(moment(date, 'YYYY-MM-DD').format('YYYY-MM-DD'));
 		date.setDate(date.getDate() + 1);
 	}

 	return dates;
 }

 function apbgfIsFirefox() {
 	return /firefox/i.test( navigator.userAgent );
 }

 function apbgfEnhanceFirefoxTimeFields( container ) {
 	if ( ! apbgfIsFirefox() ) {
 		return;
 	}
 	var $scope = container ? jQuery( container ) : jQuery( '#apbgf-staff-modal' );
 	$scope.find( '.form-start-time-slots input[type="time"], .form-end-time-slots input[type="time"]' ).each( function() {
 		var $input = jQuery( this );
 		var formatted = apbgfFormatTimeForInput( $input.val() );
 		if ( formatted !== $input.val() ) {
 			$input.val( formatted );
 		}
 		if ( $input.parent( '.apbgf-time-input-wrap' ).length ) {
 			return;
 		}
 		$input.wrap( '<div class="apbgf-time-input-wrap"></div>' );
 		jQuery(
 			'<button type="button" class="apbgf-time-picker-trigger" aria-label="Choose time">' +
 			'<i class="fa fa-clock-o" aria-hidden="true"></i></button>'
 		).insertAfter( $input );
 	} );
 }

 function apbgfFormatTimeForInput( timeStr ) {
 	if ( ! timeStr && 0 !== timeStr ) {
 		return '';
 	}
 	var parts = String( timeStr ).trim().split( ':' );
 	if ( parts.length < 2 ) {
 		return '';
 	}
 	var h = parseInt( parts[0], 10 );
 	var m = parseInt( parts[1], 10 );
 	if ( isNaN( h ) || isNaN( m ) ) {
 		return '';
 	}
 	return pad( h, 2 ) + ':' + pad( m, 2 );
 }

 function apbgfRefreshStaffTimeInputs( container ) {
 	if ( apbgfIsFirefox() ) {
 		apbgfEnhanceFirefoxTimeFields( container );
 		return;
 	}
 	var $inputs = container ? jQuery( container ).find( 'input[type="time"]' ) : jQuery( 'input[type="time"]' );
 	$inputs.each( function() {
 		var input = this;
 		var value = apbgfFormatTimeForInput( input.value );
 		try {
 			var parent = input.parentNode;
 			if ( ! parent ) {
 				return;
 			}
 			var clone = input.cloneNode( true );
 			clone.value = value;
 			parent.replaceChild( clone, input );
 		} catch ( err ) {
 			input.value = '';
 			input.value = value;
 		}
 	} );
 }

 function parseTime(s) {
 	var c = s.split(':');
 	return parseInt(c[0]) * 60 + parseInt(c[1]);
 }

 function convertHours(mins){
 	var hour = Math.floor(mins/60);
 	var mins = mins%60;
 	var converted = pad(hour, 2)+':'+pad(mins, 2);
 	return converted;
 }

 function pad (str, max) {
 	str = str.toString();
 	return str.length < max ? pad("0" + str, max) : str;
 }

 function apbgf_split_time(start_time, end_time, duration = 5, interval = 5 ) {
 	
 	var i = 1,
 	formatted_time = '',
 	start_time = start_time,
 	end_time = end_time,
 	time_slots = new Array(),
 	duration = parseInt(duration),
 	interval = parseInt(interval);
 	
 	while ( (start_time + interval) < end_time ) {
 		if ( i > 1 ) {
 			start_time += interval;
 		}
 		
 		formatted_time = `${convertHours(start_time)} - ${convertHours(start_time + duration)}`;
 		
 		time_slots.push(formatted_time);

    	start_time += duration; //Endtime check

    	i++;
    }
    
    return time_slots;
}
