<?php
add_filter( 'ninja_forms_enqueue_scripts', 'my_pikaday_modifications' );
function my_pikaday_modifications() {
	if(page_id() === 222) {		
		
		// PHP VARS
		$is_user_logged_in = is_user_logged_in();
		if( $is_user_logged_in ) {
			$balance = mycred_return_users_balance();		
				
			if( get_own_nonpremium_requests() )				
				$i_nonpremium_requests = count(get_own_nonpremium_requests());
			else
				$i_nonpremium_requests = 0;
			
			php_console_log('Balance php: ' . $balance);
			php_console_log('i_nonpremium_requests php: ' . $i_nonpremium_requests);
		}		
		
		?>
			<script>
			// START JAVASCRIPT						
			var first_selected_date;
			var first_selected_date_rounded;
			var first_selected_time;
			var second_selected_date;
			var myOptsCpy;
			var myOpts;
			var appointment_type;
			var standorte_type;
			var customDatePickerStuff;
			var datepickerObj = {
				1: {},
				2: {}
			};
			var cannot_afford_button_bound = false;				
			var bookingTextTable = init_bookingTextTable();
				
			var is_user_logged_in = "<?php echo $is_user_logged_in ?>";
			if( is_user_logged_in ) {
				var mycred_user_balance = "<?php echo $balance ?>";
				var i_nonpremium_requests = "<?php echo $i_nonpremium_requests ?>";
				console.log('Balance from js: ' + mycred_user_balance);
			}
				
			// DOCUMENT READY
			jQuery(document).ready(function() {			
				customDatePickerStuff = Marionette.Object.extend({
					initialize: function() {
						//console.log('Marionette initialize...');
						this.listenTo(Backbone.Radio.channel('pikaday'), 'init', this.modifyDatepicker);
					},
					modifyDatepicker: function(dateObject, fieldModel) {
						wait_for_element('ninja-page-id', 'create_destroy_datepicker', dateObject);
					}
				});
				new customDatePickerStuff();
			});		
				
			// ON CHANGE MULTI PART
			document.addEventListener("DOMContentLoaded", function(event) {					
				jQuery(document).on( 'nfFormReady', function( e, layoutView ) {
					// first time ready 
					let ninja_page_id = jQuery('#ninja-page-id')[0].value;
					console.log('paooo ' + ninja_page_id);
						
					if( ninja_page_id == -1 ) {
						appointment_type = jQuery('input[name=nf-field-101]:checked', '#nf-field-101-wrap').val();
						console.log('appointment_type: ' + appointment_type);
						jQuery('#nf-field-101-wrap input').on('change', function() {
						   	appointment_type = jQuery('input[name=nf-field-101]:checked', '#nf-field-101-wrap').val();
							console.log('appointment_type: ' + appointment_type);
						});
					}
					
					
					nfRadio.channel( 'nfMP' ).on('change:part', function() {
						console.log('appointment_type: ' + appointment_type);
						
						let ninja_page_id = jQuery('#ninja-page-id')[0].value;
						
						// RESET BOOKING TEXT TABLE
						reset_booking_text_table(ninja_page_id);				
						
						if( ninja_page_id == -1 ) {
							jQuery('#nf-field-101-wrap input').on('change', function() {
							   	appointment_type = jQuery('input[name=nf-field-101]:checked', '#nf-field-101-wrap').val();
								console.log('appointment_type: ' + appointment_type);
							});
						}
						else if( ninja_page_id == 1 ) {
							// ON CHANGE START-UHRZEIT
							jQuery('select#nf-field-57').on('change', function() {
								console.log('changed 57 to ' + this.value);
								let uhrzeit = jQuery( "#nf-field-57 option:selected" ).text();
								bookingTextTable['start-datum']['value_uhrzeit'] = uhrzeit;
								refresh_booking_text_table(ninja_page_id);
							});							
							refresh_booking_text_table(ninja_page_id);							
						}				
						else if( ninja_page_id == 2 ) {					
							// ON CHANGE END-UHRZEIT
							jQuery('select#nf-field-53').on('change', function() {
								console.log('changed 53 to ' + this.value);
								let uhrzeit = jQuery( "#nf-field-53 option:selected" ).text();
								bookingTextTable['end-datum']['value_uhrzeit'] = uhrzeit;
								refresh_booking_text_table(ninja_page_id);
							});	
							
							if( appointment_type == 'sofort' ) { 
								console.log('SOFORT AND 2');
								let dateObj = next_businessDay_dateObj();
								dateObj = roundMinutes(dateObj, 'object');
								let start_uhrzeit = dateObj.getHours() + ':' + (dateObj.getMinutes()<10?'0':'') + dateObj.getMinutes();
								let start_datum = german_date_string(dateObj);								
								bookingTextTable['start-datum']['value'] = start_datum;		
								bookingTextTable['start-datum']['value_uhrzeit'] = start_uhrzeit;
							}
							refresh_booking_text_table(ninja_page_id);
						}
						else if( ninja_page_id == 3 ) {
							// ON CHANGE DIENSTLEISTUNG
							let ausgewaehlt = jQuery( "#nf-field-50 option:selected" ).text();
							if( ausgewaehlt == 'Bitte auswählen...' ) {
								bookingTextTable['dienstleistung']['value'] = '-';
							}
							else {
								ausgewaehlt = trim_string(ausgewaehlt, 43);
								bookingTextTable['dienstleistung']['value'] = ausgewaehlt;
							}							
							
							jQuery('select#nf-field-50').on('change', function() {
								console.log('changed 50 to ' + this.value);
								let ausgewaehlt = jQuery( "#nf-field-50 option:selected" ).text();
								if( ausgewaehlt == 'Bitte auswählen...' ) {
									bookingTextTable['dienstleistung']['value'] = '-';
								}
								else {
									ausgewaehlt = trim_string(ausgewaehlt, 43);
									bookingTextTable['dienstleistung']['value'] = ausgewaehlt;
								}	
								refresh_booking_text_table(ninja_page_id);
							});	
							refresh_booking_text_table(ninja_page_id);
						}
						else if( ninja_page_id == 4 ) {
							// ON CHANGE STANDORTE
							standorte_type = jQuery('input[name=nf-field-113]:checked', '#nf-field-113-wrap').val();
							jQuery('#nf-field-113-wrap input').on('change', function() {
								standorte_type = jQuery('input[name=nf-field-113]:checked', '#nf-field-113-wrap').val();
							});
							refresh_booking_text_table(ninja_page_id);
						}
						else if( ninja_page_id == 5 ) {
							var venuesChecked = new Array();
							jQuery("#modal-5e6603a34d72d .checkbox-venue").change(function() {								
								if(this.checked) {
									venuesChecked.push(this.value);
								}
								else {
									removeA(venuesChecked, this.value);
								}

								if (typeof venuesChecked !== 'undefined' && venuesChecked.length > 0) {
									let value = venuesChecked.length + ' erfolgreich ausgewählt';				
									bookingTextTable['standorte']['value'] = value;
								}
								else if (typeof venuesChecked !== 'undefined' && venuesChecked.length == 0) {
									let value = '-';	
									bookingTextTable['standorte']['value'] = value;
								}
								refresh_booking_text_table(ninja_page_id);
							});
							
							refresh_booking_text_table(ninja_page_id);
						}
						else if( ninja_page_id == 6 ) {
							// ON CHANGE STANDORTE
							if( standorte_type == 'berlinweit' ) {
								bookingTextTable['standorte']['value'] = 'Berlinweit';	
							}
							else if( standorte_type == 'standorte-auswaehlen' ) {
								//bookingTextTable['standorte']['value'] = 'Berlinweit';	
							}
							refresh_booking_text_table(ninja_page_id);
							
							// MAKE IT RAIN
							jQuery('#nf-field-59').on('click', function() {
								makeItRain();
							});
						}			
						
						
					});				
				});
			});
				
			function indicator_bookingTextTable(ninja_page_id) {
				console.log('here');
				jQuery('.indicator').each(function(i, obj) {
					obj.innerHTML = '';
				});
				
				if( ninja_page_id == 1 )
					jQuery('#start-datum .indicator').append('<i class="fas fa-long-arrow-alt-right"></i>');
				else if( ninja_page_id == 2 )
					jQuery('#end-datum .indicator').append('<i class="fas fa-long-arrow-alt-right"></i>');
				else if( ninja_page_id == 3 )
					jQuery('#dienstleistung .indicator').append('<i class="fas fa-long-arrow-alt-right"></i>');
				else if( ninja_page_id == 4 )
					jQuery('#standorte .indicator').append('<i class="fas fa-long-arrow-alt-right"></i>');
				else if( ninja_page_id == 5 )
					jQuery('#standorte .indicator').append('<i class="fas fa-long-arrow-alt-right"></i>');
			}
				
			function init_bookingTextTable() {
				return {
						'start-datum': {
							'label': 'Start-Datum:',
							'value': '-',
							'value_uhrzeit': '-',
						},
						'end-datum': {
							'label': 'End-Datum:',
							'value': '-',
							'value_uhrzeit': '-',
						},
						'dienstleistung': {
							'label': 'Dienstleistung:',
							'value': '-',
						},
						'standorte': {
							'label': 'Bürgerämter:',
							'value': '-',
						},
						'preis': {
							'label': 'Preis:',
							'value': '-',
						},
					};
			}
			
			function reset_booking_text_table(ninja_page_id) {
				if( ninja_page_id == -1 ) {
					jQuery('#booking-text .pp-sub-heading p')[0].textContent = 'Terminsnipe ist dein Portal für die smarte Terminsuche. Bleib\' im Bett, auf der Couch, oder lade deine Mutter zum Essen ein. Schluss mit Warteschleifen. Mach\' was Besseres mit deiner Zeit. Wir übernehmen das.';
					bookingTextTable = init_bookingTextTable();
				}
				else if( ninja_page_id == 1 ) {
					bookingTextTable = init_bookingTextTable();
				}
				else if( ninja_page_id == 2 ) {					
					bookingTextTable['end-datum']['value'] = '-';		
					bookingTextTable['end-datum']['value_uhrzeit'] = '-';
					bookingTextTable['dienstleistung']['value'] = '-';	
				}
				else if( ninja_page_id == 3 ) {					
					bookingTextTable['dienstleistung']['value'] = '-';	
				}
				else if( ninja_page_id == 4 ) {					
					bookingTextTable['standorte']['value'] = '-';	
				}
				else if( ninja_page_id == 5 ) {					
					bookingTextTable['standorte']['value'] = '-';	
				}
			}
				
			function refresh_booking_text_table(ninja_page_id) {
				// TABLE
				let innerHTML = 		'<table id="booking-text-table">';
				if ( is_user_logged_in ) {
					innerHTML = innerHTML + '<tr id="preis">\
												<td class="indicator"></td><td class="min"></td><td></td>\
											</tr>';
				}
				innerHTML = innerHTML +		'<tr id="start-datum">\
												<td class="indicator"></td><td class="min"></td><td><span id="start-datum-value"></span> <span id="start-uhrzeit-value"></span></td>\
											</tr>\
											<tr id="end-datum">\
												<td class="indicator"></td><td class="min"></td><td><span id="end-datum-value"></span> <span id="end-uhrzeit-value"></span></td>\
											</tr>\
											<tr id="dienstleistung">\
												<td class="indicator"></td><td class="min"></td><td></td>\
											</tr>\
											<tr id="standorte">\
												<td class="indicator"></td><td class="min"></td><td></td>\
											</tr>\
										</table>';				
				jQuery('#booking-text .pp-sub-heading p')[0].innerHTML = innerHTML;
				
				// PREIS
				if ( is_user_logged_in ) {
					jQuery('#booking-text-table #preis td')[1].textContent = bookingTextTable['preis']['label'];
					jQuery('#booking-text-table #preis td')[2].innerHTML = bookingTextTable['preis']['value'];
				}				
				
				// START-DATUM
				jQuery('#booking-text-table #start-datum td')[1].textContent = bookingTextTable['start-datum']['label'];
				jQuery('#start-datum-value')[0].textContent = bookingTextTable['start-datum']['value'];
				if( bookingTextTable['start-datum']['value'] != '-' ) {					
					jQuery('#start-uhrzeit-value')[0].textContent = bookingTextTable['start-datum']['value_uhrzeit'];
				}				
				
				// END-DATUM
				jQuery('#booking-text-table #end-datum td')[1].textContent = bookingTextTable['end-datum']['label'];
				jQuery('#end-datum-value')[0].textContent = bookingTextTable['end-datum']['value'];
				if( bookingTextTable['end-datum']['value'] != '-' ) {					
					jQuery('#end-uhrzeit-value')[0].textContent = bookingTextTable['end-datum']['value_uhrzeit'];
				}
				
				// DIENSTLEISTUNG
				jQuery('#booking-text-table #dienstleistung td')[1].textContent = bookingTextTable['dienstleistung']['label'];
				jQuery('#booking-text-table #dienstleistung td')[2].textContent = bookingTextTable['dienstleistung']['value'];
				
				// STANDORTE
				jQuery('#booking-text-table #standorte td')[1].textContent = bookingTextTable['standorte']['label'];
				jQuery('#booking-text-table #standorte td')[2].textContent = bookingTextTable['standorte']['value'];
				
				// INDICATOR
				indicator_bookingTextTable(ninja_page_id);
			}
				
			function german_date_string(dateObj) {
				var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric', };
				return dateObj.toLocaleDateString("de-DE");
			}

			function create_destroy_datepicker(selector, dateObject) {
				console.log('in create_destroy_datepicker');
				let ninja_page_id = jQuery('#ninja-page-id')[0].value;

				if (ninja_page_id == 1 && typeof datepickerObj[1]['dateObject'] != "undefined") {
					console.log('dateObject1 already defined');
					
					dateObject.pikaday.destroy(); // WE DONT NEED A NEW PIKADAY				
					apply_custom_datepicker_changes(ninja_page_id, dateObject); // SHOW	& SET DEFAULT VALUE
				} 
				else if (ninja_page_id == 2 && typeof datepickerObj[2]['dateObject'] != "undefined") {
					console.log('dateObject2 already defined');
					
					dateObject.pikaday.destroy(); // WE DONT NEED A NEW PIKADAY					
					apply_custom_datepicker_changes(ninja_page_id, dateObject); // SHOW	& SET DEFAULT VALUE
				}
				else {
					console.log('creating and saving dateObject' + ninja_page_id + ' now...');
					// SAVE DATEPICKER OBJ
					datepickerObj[ninja_page_id]['dateObject'] = dateObject;
					apply_custom_datepicker_changes(ninja_page_id);
				}
			}
				
			function next_businessDay_dateObj() {
				let server_time = new Date();
				//let server_time = new Date("April 22, 2020 08:15:00");
				console.log('server_time: ' + server_time);

				if (server_time.getHours() < businessHoursObj['start']['hours']) {
					console.log('Before ' + businessHoursObj['start']['hours'] + ' o clock');      
					var dateObj = next_business_day_with_time(server_time, businessHoursObj['start']['hours'], businessHoursObj['start']['minutes'], businessHoursObj['start']['seconds']);
				}
				else if (server_time.getHours() >= businessHoursObj['end']['hours']) {
					console.log('After ' + businessHoursObj['end']['hours'] + ' o clock');        
					let tomorrow = addDays(server_time, 1);
					var dateObj = next_business_day_with_time(tomorrow, businessHoursObj['start']['hours'], businessHoursObj['start']['minutes'], businessHoursObj['start']['seconds']);
				} 
				else {
					console.log('Between ' + businessHoursObj['start']['hours'] + '-' + businessHoursObj['end']['hours'] + ' o clock');
					dateObj = cloneDate(server_time);
					if( isWeekend(dateObj) ) {
					  	let tomorrow = addDays(dateObj, 1);
					  	var dateObj = next_business_day_with_time(tomorrow, businessHoursObj['start']['hours'], businessHoursObj['start']['minutes'], businessHoursObj['start']['seconds']);
						dateObj = roundMinutes(dateObj, 'object');
					}
				}

				return dateObj;
			}

			function cloneDate(date) {
			   return new Date(date.getTime());
			}

			function next_business_day_with_time(dateObj, hours, minutes, seconds) {
			  if( !isWeekend(dateObj) ) {
				console.log('isWeekend: 0');
			  }
			  else {
				console.log('isWeekend: 1');
				dateObj = get_next_business_day(dateObj);      
			  }

			  dateObj.setHours(hours);
			  dateObj.setMinutes(minutes);
			  dateObj.setSeconds(seconds);

			  return dateObj;
			}

			function get_next_business_day(dateObj) {
			  let cloneDateObj = cloneDate(dateObj);
			  var i = 0;
			  while( isWeekend(cloneDateObj) ) {
				i++;
				cloneDateObj = addDays(cloneDateObj, i);
			  }

			  return addDays(dateObj, i);
			}

			function addDays(date, days) {
			  var result = new Date(date);
			  result.setDate(result.getDate() + days);
			  return result;
			}

			function isWeekend(dateObj) {
			  var day = dateObj.getDay();

			  return (day === 6) || (day === 0); 
			}
				
			function DateDiff(d1, d2, fswitch) {
				//console.log('Comparing:');
				//console.log(d1);
				//console.log(d2);
				
				if (fswitch == 'inDays') {
					var t2 = d2.getTime();
					var t1 = d1.getTime();

					return parseInt((t2-t1)/(24*3600*1000));
				}
				else if (fswitch == 'inWeeks') {
					var t2 = d2.getTime();
					var t1 = d1.getTime();

					return parseInt((t2-t1)/(24*3600*1000*7));
				}
				else if (fswitch == 'inMonths') {
					var d1Y = d1.getFullYear();
					var d2Y = d2.getFullYear();
					var d1M = d1.getMonth();
					var d2M = d2.getMonth();

					return (d2M+12*d2Y)-(d1M+12*d1Y);
				}
				else if (fswitch == 'inYears') {
					return d2.getFullYear()-d1.getFullYear();
				}
			}
				
			function is_premium_day(date) {
				let i = DateDiff(new Date(), date, 'inDays');				
				let is_premium_day = 0;
				for (var key in fastsnipeObj) {
					if (fastsnipeObj.hasOwnProperty(key)) {						
						let day_end = fastsnipeObj[key]['day_end'] - 2;
						if (i <= day_end) {
							is_premium_day = 1;
							break;
						}					
					}
				}
			
				return is_premium_day;
			}
				
			function check_premium(date, price = null) {
				let can_afford;
				let is_premium = is_premium_day(date);
				if ( is_premium ) {
					is_premium = 1;
					if ( !price ) {
						price = get_fastsnipe_price(date);
					}				
					can_afford = can_afford_fastsnipe(price);
					if ( !can_afford ) {					
						can_afford = 0;
					}
					else if ( can_afford ) {
						can_afford = 1;	
					}
				}
				else {
					console.log('No premium day');
				}
				
				return [can_afford, price, is_premium];
			}
				
			function check_premium_after(can_afford, selector1, selector2, is_premium, price, ninja_page_id) {
				if( is_premium ) {
					if( can_afford ) {
						console.log('User can purchase');
					}
					else if( !can_afford ) {
						if( can_afford === 0 ) {
							console.log('User has too few coins.');
							jQuery('#cannot-afford-modal').click();						
							
							if ( ninja_page_id == 1 ) {
								jQuery( "#cannot-afford-modal-close" ).click(function() {
									setTimeout(function(){
									  jQuery('#' + selector2).click();
									}, 200);													
								});
							}
							else if ( ninja_page_id == 2 ) {
								if( !cannot_afford_button_bound ) {
								   jQuery( ".uabb-modal-close" ).click(function() {
										jQuery('.nf-previous').click();
									});
									jQuery( "#cannot-afford-modal-close" ).click(function() {				
										jQuery('.uabb-modal-close').click();
										jQuery('#nf-label-class-field-101-1').click();
										jQuery('.nf-next').click();
									});
									cannot_afford_button_bound = 1;
								}
								
							}	
							
							if ( jQuery('#' + selector2).length ) {
								jQuery('#' + selector2)[0].value = '';
							}										
							allow_next(0, selector1);
						}														
					}	
				}
				else {
					console.log('No premium day');
					if( i_nonpremium_requests >= 1 ) {
						console.log('User already has 1 ongoing free snipe');
						jQuery('#nonpremium-limit-modal').click();
						jQuery( "#nonpremium-limit-close" ).click(function() {
							jQuery('.uabb-modal-close').click();							
							setTimeout(function(){
								jQuery('#' + selector2).click();
							}, 200);					
						});
						if ( jQuery('#' + selector2).length ) {
							jQuery('#' + selector2)[0].value = '';
						}	
						allow_next(0, selector1);
					}
				}			
			}
				
			function can_afford_fastsnipe(price) {
				let can_afford = 0;										
				let diff = mycred_user_balance - price;
				console.log('price: ' + price);	
				console.log('diff: ' + diff);
				if ( diff >= 0 ) {
					can_afford = 1;
				}

				return can_afford;
			}
				
			function get_fastsnipe_price(date) {
				let price = undefined;
				let i = DateDiff(new Date(), date, 'inDays');				
				for (var key in fastsnipeObj) {
					if (fastsnipeObj.hasOwnProperty(key)) {						
						let day_end = fastsnipeObj[key]['day_end'] - 2;
						if (i <= day_end) {
							price = fastsnipeObj[key]['price'];
							break;
						}					
					}
				}
				
				return price;
			}
				
			function apply_custom_datepicker_changes(ninja_page_id) {
				console.log('in apply_custom_datepicker_changes');
				var dateObject = datepickerObj[ninja_page_id]['dateObject'];
				var show_datepicker;
				console.log(dateObject);

				if (ninja_page_id == 1) {
					var single_text_id = 'nf-field-190';
				}
				else if (ninja_page_id == 2) {
					var single_text_id = 'nf-field-189';
				}
				
				// CONFIG
				dateObject.pikaday._o.maxDate = pikaday_maxDate();
				dateObject.pikaday._o.disableWeekends = true;
				dateObject.pikaday._o.numberOfMonths = 3;
				dateObject.pikaday._o.firstDay = 1;
				dateObject.pikaday._o.i18n = {
					previousMonth: 'Vormonat',
					nextMonth: 'Nächster Monat',
					months: ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'],
					weekdays: ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'],
					weekdaysShort: ['So.', 'Mo.', 'Di.', 'Mi.', 'Do.', 'Fr.', 'Sa.']
				};
				dateObject.pikaday._o.onOpen = function() {
					console.log('onOpen');

					var rect = document.getElementById('booking-text').getBoundingClientRect();					
					//console.log(rect.top, rect.right, rect.bottom, rect.left);
					let left = rect.left + 55;
					let top = rect.top - 0;
					jQuery('.pika-single').css({
						left: left + 'px',
						top: top + 'px'
					});

					// IF LOGGED IN: COLORIZE DATES
					if( is_user_logged_in ) {
						if( ninja_page_id != 2 ) {
							console.log('colorizing...');
							colorize_pikaday_spans();
							inject_pikaday_legend("//div[contains(@class, 'pika-single') and not(contains(@class, 'is-hidden'))]", 'label');					
						}
						else if( ninja_page_id == 2 ) {			
							if( appointment_type == 'sofort' ) {
								//let dateObj = new Date();
								
								let dateObj = next_businessDay_dateObj();
								console.log('modified date: ' + dateObj.toString());
								
								pika_change_bg_color(dateObj.getUTCDate(), dateObj.getUTCMonth()+1, dateObj.getUTCFullYear(), 'lightgrey');				
								inject_pikaday_legend("//div[contains(@class, 'pika-single') and not(contains(@class, 'is-hidden'))]", 'start_end');
							}
							else if( appointment_type == 'zeitraum' ) {
								let dateObj = first_selected_date;
								pika_change_bg_color(dateObj.getUTCDate()+1, dateObj.getUTCMonth()+1, dateObj.getUTCFullYear(), 'lightgrey');	
								inject_pikaday_legend("//div[contains(@class, 'pika-single') and not(contains(@class, 'is-hidden'))]", 'start_end');
							}
							
						}
					}					
				};				

				if (ninja_page_id == 1) {
					console.log('----------');
					show_datepicker = 1;
					
					defaultPart('nf-field-190', dateObject); // INJECT TEXT BUTTON, allow_next(0)					
					//appointment_type = 'zeitraum'; // TYPE							
					set_start_time_for_today('nf-field-57', dateObject); // SET DATE AND TIME	

					// ON SELECT
					dateObject.pikaday._o.onSelect = function() {
						first_selected_date = dateObject.pikaday.getDate();
						on_select_single_day_logic('nf-field-57', first_selected_date, dateObject);						
						jQuery( '#nf-field-190' ).val( dateObject.pikaday.toString('YYYY-MM-DD') ).trigger( 'change' ); // WRITE SELECTED DATE INTO TEXT LINE
						allow_next(1, 'nf-field-190-wrap');
						
						// IF LOGGED IN: CHECK DAY AGAINST COINS BALANCE					
						if ( is_user_logged_in ) {						
							let [can_afford, price, is_premium] = check_premium(first_selected_date);
							bookingTextTable['preis']['value'] = price + ' <img src="http://zinomedia.de/terminsnipe/wp-content/uploads/sites/6/2020/03/630865.svg" alt="fastcoins">';	
							console.log('can_afford: ' + can_afford + ' | price: ' + price + ' | is_premium: ' + is_premium);
							check_premium_after(can_afford, 'nf-field-190-wrap', 'nf-field-190', is_premium, price, ninja_page_id);			
						}
						
						// BOOKING-TEXT-TABLE
						let start_datum = german_date_string(first_selected_date);
						let start_uhrzeit = jQuery( "#nf-field-57 option:selected" ).text();
						bookingTextTable['start-datum']['value'] = start_datum;	
						bookingTextTable['start-datum']['value_uhrzeit'] = start_uhrzeit;		
						refresh_booking_text_table(ninja_page_id);			
					};

					// TIME ON CHANGE
					jQuery('#nf-field-57').on('change', function() {
						first_selected_time = this.value;
					});
				}
				else if (ninja_page_id == 2) {
					console.log('----------');
					
					// TYPE
					//if (!appointment_type)
					//	appointment_type = 'sofort';
					
					if ( appointment_type == 'sofort' ) {
						console.log('sofort fired');
						set_start_time_for_today('nf-field-53', dateObject);
						show_datepicker = 1;
						if ( is_user_logged_in ) {						
							let [can_afford, price, is_premium] = check_premium(new Date(), fastsnipeObj[1]['price']);
							console.log('can_afford: ' + can_afford + ' | price: ' + price + ' | is_premium: ' + is_premium);
							show_datepicker = can_afford;
							check_premium_after(can_afford, 'nf-field-190-wrap', 'nf-field-190', is_premium, price, ninja_page_id );
						}
					}
					else if (appointment_type == 'zeitraum') {
						console.log('zeitraum fired');
						dateObject.pikaday._o.minDate = first_selected_date;
						show_datepicker = 1;
					}
					
					defaultPart('nf-field-189', dateObject); // INJECT TEXT BUTTON, allow_next(0)	
				
					jQuery("#nf-field-53").val(jQuery("#nf-field-53 option:last").val());	// SELECT LAST OPTION

					// EVENTS
					dateObject.pikaday._o.onSelect = function() {
						second_selected_date = dateObject.pikaday.getDate();

						if (appointment_type == 'zeitraum') {
							if (second_selected_date.setHours(0, 0, 0, 0) == first_selected_date.setHours(0, 0, 0, 0) && same_day(first_selected_date, new Date())) {
								console.log('Same dates picked and dates are today');
								setTimeRange('nf-field-53', first_selected_time, '18', 2); // OFFSET 2 = ONE HOUR LATER
							} else if (second_selected_date.setHours(0, 0, 0, 0) == first_selected_date.setHours(0, 0, 0, 0) && !same_day(first_selected_date, new Date())) {
								console.log('Same dates picked and but dates are not today');
								setTimeRange('nf-field-53', first_selected_time, '18', 2); // OFFSET 2 = ONE HOUR LATER
							} else {
								setTimeRange('nf-field-53', '07', '18');
							}
						} else if (appointment_type == 'sofort') {
							on_select_single_day_logic('nf-field-53', second_selected_date, dateObject);
						}
						
						jQuery("#nf-field-53").val(jQuery("#nf-field-53 option:last").val()); // SELECT LAST OPTION						
						jQuery( '#nf-field-189' ).val( dateObject.pikaday.toString('YYYY-MM-DD') ).trigger( 'change' ); // WRITE SELECTED DATE INTO TEXT LINE
						allow_next(1, 'nf-field-189-wrap');
						
						// IF LOGGED IN: CHECK DAY AGAINST COINS BALANCE						
						if ( appointment_type == 'sofort' ) {
							if ( is_user_logged_in ) {							
								let [can_afford, price, is_premium] = check_premium(new Date(), fastsnipeObj[1]['price']);
								console.log('can_afford: ' + can_afford + ' | price: ' + price + ' | is_premium: ' + is_premium);							
								check_premium_after(can_afford, 'nf-field-189-wrap', 'nf-field-189', is_premium, price);						
							}
						}
						
						// BOOKING-TEXT-TABLE
						let end_datum = german_date_string(second_selected_date);
						let end_uhrzeit = jQuery( "#nf-field-53 option:selected" ).text();
						bookingTextTable['end-datum']['value'] = end_datum;	
						bookingTextTable['end-datum']['value_uhrzeit'] = end_uhrzeit;		
						refresh_booking_text_table(ninja_page_id);							
						if ( is_user_logged_in ) {			
													
						}
						
					};

				}

				// ADJUST / RELOAD CALENDAR
				dateObject.pikaday.adjustCalendars();
				if (show_datepicker)
					dateObject.pikaday.show();
			}		
				
			function allow_next(bool, selector) {
				// DEFAULT
				jQuery('#' + selector).removeClass('nf-fail nf-error nf-pass');
				jQuery(".nf-next").css("pointer-events", "auto");

				if (bool == 1) {
					jQuery('#' + selector).addClass('nf-pass');
					jQuery(".nf-next").css("pointer-events", "auto");
				} else if (bool == 0) {
					jQuery('#' + selector).addClass('nf-fail nf-error');
					jQuery(".nf-next").css("pointer-events", "none");
				}
			}			

			function setTimeRange(selector, startTime, endTime, offsetStart = 0, offsetEnd = 0) {
				console.log('startTime: ' + startTime + '\tendTime: ' + endTime + '\toffsetStart: ' + offsetStart + '\toffsetEnd: ' + offsetEnd);
				// GET OPTIONS			
				if (!myOptsCpy) {
					var options = jQuery('#' + selector)[0].options
					myOpts = Array.prototype.slice.call(options);
				}
				myOptsCpy = myOpts;

				// GET INDICES	
				for (var i = 0; i < myOpts.length; i++) {
					if (myOpts[i].value == startTime) {
						var startIndex = i + offsetStart;
						//console.log('startIndex @ ' + startIndex);						
					}
					if (myOpts[i].value == endTime) {
						var endIndex = i + offsetEnd;
						//console.log('endIndex @index ' + i);
					}
				}

				if (startIndex > myOpts.length)
					startIndex = myOpts.length;

				if (endIndex > myOpts.length)
					endIndex = myOpts.length

				if (endIndex < startIndex) {
					endIndex = myOpts.length;
					startIndex = myOpts.length - 1;
				}

				// REMOVE ALL UNWANTED					
				myOptsCpy = myOptsCpy.slice(startIndex, endIndex + 1);

				// CLEAR
				jQuery('#' + selector)[0].options.length = 0;

				// FILL
				for (i = 0; i < myOptsCpy.length; i++) {
					jQuery('#' + selector).append(
						jQuery("<option></option>")
						.text(myOptsCpy[i].text)
						.val(myOptsCpy[i].value)
					);
				}

				first_selected_time = myOptsCpy[0].value;
			}

			function on_select_single_day_logic(selector, selected_date, dateObject) {
				if (same_day(selected_date, new Date())) {
					console.log('Selected same day');
					set_start_time_for_today(selector, dateObject);
				} else {
					console.log('Another day selected');
					setTimeRange(selector, '07', '18');
				}
			}

			function defaultPart(selector, dateObject) {
				jQuery('#' + selector)[0].value = '';
				allow_next(0, selector + '-wrap');
				jQuery('#' + selector).click(function() {
					dateObject.pikaday.show();
					return false;
				});
			}

			function set_start_time_for_today(selector, dateObject) {
				// SERVER TIME
				var server_time = new Date();
				//var server_time = new Date("March 5, 2020 11:15:00");
				//console.log('server_time: ' + server_time);

				// TODAY
				var today = new Date(new Date().setDate(new Date().getDate() - 1));

				if (server_time.getHours() < 7) { // BEFORE 7:00
					//console.log('Before 7:00');
					var pikaday_minDate = today;
				} else if (server_time.getHours() >= 18) { // AFTER 18:00 -> SELECT NEW DAY
					//console.log('After 18:00');
					var pikaday_minDate = today.setDate(today.getDate() + 1);
				} else { // SELECT CURRENT DAY WITH CURRENT TIME
					//console.log('Between 7:00 - 18:00');
					var pikaday_minDate = today;

					var start_time = roundMinutes(server_time);
					//console.log('start_time: ' + start_time);

					// DEFINE TIME RANGE
					setTimeRange(selector, start_time, '18');
				}

				// PIKADAY START DAY
				dateObject.pikaday._o.minDate = pikaday_minDate;
				//console.log('pikaday_minDate: ' + pikaday_minDate);
			}

			function same_day(d1, d2) {
				return d1.getFullYear() === d2.getFullYear() &&
					d1.getMonth() === d2.getMonth() &&
					d1.getDate() === d2.getDate();
			}

			function roundMinutes(date, fswitch = null) {
				if (date.getMinutes() < 30) {
					//console.log('Fill up to :30');
					var rounded_date = date;
					rounded_date.setMinutes(30);
				} else if (date.getMinutes() >= 30) {
					//console.log('Fill up to :00 next hour');
					var rounded_date = date;
					rounded_date.setMinutes(0);
					rounded_date.setHours(rounded_date.getHours() + 1);
				}
				rounded_date.setSeconds(0);
				first_selected_date_rounded = rounded_date;
				
				if( !fswitch )
					return date2start_time(rounded_date);
				else if( fswitch == 'object' )
					return rounded_date;
			}

			function date2start_time(date) {
				if (date.getMinutes() == 0)
					var start_time = date.getHours();
				else if (date.getMinutes() == 30)
					var start_time = date.getHours() + '-' + date.getMinutes();

				return start_time;
			}			
			// END JAVASCRIPT

			</script>				
		<?php
	}
}