// source --> https://urbanelephantsuites.gr/wp-content/plugins/beds24-online-booking/js/beds24-datepicker.js?ver=6.8.5 
var beds24dayname = "Day";


jQuery(document).ready(function($) {
	$("#datepicker").datepicker({
	buttonImage: WPURLS.siteurl + '/wp-content/plugins/beds24-online-booking/theme-files/include/ic_calendar2.png',
	buttonImageOnly: true,
	changeMonth: true,
	changeYear: true,
	showOn: 'both',
	dateFormat: 'yy-mm-dd',
	beforeShow: readdatepicker, 
	onSelect: updatedatepicker
});
	
var beds24lang = jQuery('#fdate_lang').val();
var beds24getscript = false;
switch (beds24lang) {
case "da":  
  beds24dayname="Dag";
	beds24getscript = WPURLS.siteurl + "/wp-content/plugins/beds24-online-booking/js/ui/i18n/datepicker-da.js";
  break;
case "de":  //german
  beds24dayname="Tag";
	beds24getscript = WPURLS.siteurl + "/wp-content/plugins/beds24-online-booking/js/ui/i18n/datepicker-de.js";
  break;
case "el":  //greek
  beds24dayname="Ημέρα";
  beds24getscript = WPURLS.siteurl + "/wp-content/plugins/beds24-online-booking/js/ui/i18n/datepicker-el.js";
  break;
case "es":  //spanish
  beds24dayname="Dia";
	beds24getscript = WPURLS.siteurl + "/wp-content/plugins/beds24-online-booking/js/ui/i18n/datepicker-es.js";
  break;
case "fi":  
  beds24dayname="Päivä";
	beds24getscript = WPURLS.siteurl + "/wp-content/plugins/beds24-online-booking/js/ui/i18n/datepicker-fi.js";
  break;
case "fr":  //french
  beds24dayname="Jour";
	beds24getscript = WPURLS.siteurl + "/wp-content/plugins/beds24-online-booking/js/ui/i18n/datepicker-fr.js";
  break;
case "it":  //italian
  beds24dayname="Giorno";
	beds24getscript = WPURLS.siteurl + "/wp-content/plugins/beds24-online-booking/js/ui/i18n/datepicker-it.js";
  break;        
case "ja":  
  beds24dayname="日";
	beds24getscript = WPURLS.siteurl + "/wp-content/plugins/beds24-online-booking/js/ui/i18n/datepicker-ja.js";
  break;
case "lt":  
  beds24dayname="Diena";
	beds24getscript = WPURLS.siteurl + "/wp-content/plugins/beds24-online-booking/js/ui/i18n/datepicker-lt.js";
  break;
case "nl":  
  beds24dayname="Dag";
	beds24getscript = WPURLS.siteurl + "/wp-content/plugins/beds24-online-booking/js/ui/i18n/datepicker-nl.js";
  break;
case "no":  
  beds24dayname="Dag";
	beds24getscript = WPURLS.siteurl + "/wp-content/plugins/beds24-online-booking/js/ui/i18n/datepicker-no.js";
  break;
case "pl":  
  beds24dayname="Dzień";
	beds24getscript = WPURLS.siteurl + "/wp-content/plugins/beds24-online-booking/js/ui/i18n/datepicker-pl.js";
  break;
case "pt":  //portuges
  beds24dayname="Dia";
	beds24getscript = WPURLS.siteurl + "/wp-content/plugins/beds24-online-booking/js/ui/i18n/datepicker-pt.js";
  break;
case "ru":  
  beds24dayname="День";
	beds24getscript = WPURLS.siteurl + "/wp-content/plugins/beds24-online-booking/js/ui/i18n/datepicker-ru.js";
  break;
case "sk":  
  beds24dayname="Deň";
	beds24getscript = WPURLS.siteurl + "/wp-content/plugins/beds24-online-booking/js/ui/i18n/datepicker-sk.js";
  break;
case "sl":  
  beds24dayname="Dan";
	beds24getscript = WPURLS.siteurl + "/wp-content/plugins/beds24-online-booking/js/ui/i18n/datepicker-sl.js";
  break;
case "sv":  
  beds24dayname="dag";
	beds24getscript = WPURLS.siteurl + "/wp-content/plugins/beds24-online-booking/js/ui/i18n/datepicker-sv.js";
  break;
case "tr":  
  beds24dayname="Gün";
	beds24getscript = WPURLS.siteurl + "/wp-content/plugins/beds24-online-booking/js/ui/i18n/datepicker-tr.js";
  break;
case "zh":  
  beds24dayname="日";
	beds24getscript = WPURLS.siteurl + "/wp-content/plugins/beds24-online-booking/js/ui/i18n/datepicker-zh-CN.js";
  break;
default: //default english
	beds24dayname="Day";
	if(document.getElementById("fdate_monthyear")) {fdate_monthyear_changed ();}
break;
}
if (beds24getscript) {
	$.getScript(beds24getscript).done(function() {if(document.getElementById("fdate_monthyear")) {fdate_monthyear_changed();}});
}

$( "#fdate_monthyear" ).change(function() {
	fdate_monthyear_changed();
});
});

function readdatepicker() {
	jQuery('#datepicker').val(jQuery('#fdate_monthyear').val() + '-' + jQuery('#fdate_date').val());
	return {};
}

function updatedatepicker(date) {
	jQuery('#fdate_monthyear').val(date.substring(0, 7));
	fdate_monthyear_changed ();
	jQuery('#fdate_date').val(parseInt(date.substring(8),10));
}

function fdate_monthyear_changed () {
	var dd = jQuery('#fdate_date').val();
	var mm = jQuery('#fdate_monthyear').val();
	jQuery('#fdate_date').empty();
	var options = new Array();
	options [0] = beds24dayname;
	if (mm==0) {
		for (i=1; i<=31; i++) {
			options[i] = i;
		}
	} else {
		year = parseInt(jQuery('#fdate_monthyear').val().substring(0, 4),10);
		month = parseInt(jQuery('#fdate_monthyear').val().substring(5, 7),10);
		for (i=1; i<=31; i++) {
			var d = new Date(year, month-1, i);	
			var n = d.getDay();
			var w = jQuery("#datepicker").datepicker("option","dayNamesShort");
			if (w == undefined) {
				w = jQuery("#datepicker").datepicker("option","dayNamesMin");
			}
			if (typeof w[n] == 'string' || w[n] instanceof String) {
				options[i] = w[n] + ' ' + i;
			}	else {
				options[i] =  i;
			}
		}
	}
	jQuery.each(options, function(value, key) {
		jQuery('#fdate_date').append(jQuery("<option></option>").attr("value", value).html(key));
	});
	jQuery('#fdate_date').val(dd);
};
// source --> https://urbanelephantsuites.gr/wp-content/plugins/halu-booking-widget/public/js/halu-booking-widget-public.js?ver=1.0.0 
(function($) {
    'use strict';
    /**
     * All of the code for your public-facing JavaScript source
     * should reside in this file.
     *
     * Note: It has been assumed you will write jQuery code here, so the
     * $ function reference has been prepared for usage within the scope
     * of this function.
     *
     * This enables you to define handlers, for when the DOM is ready:
     *
     * $(function() {
     *
     * });
     *
     * When the window is loaded:
     *
     * $( window ).load(function() {
     *
     * });
     *
     * ...and/or other possibilities.
     *
     * Ideally, it is not considered best practise to attach more than a
     * single DOM-ready or window-load handler for a particular page.
     * Although scripts in the WordPress core, Plugins and Themes may be
     * practising this, we should strive to set a better example in our own work.
     */
    jQuery(document).ready(function() {

        $('#checkin,#checkout,#numchild,#numperson').change(function() {
            var person = $('#numperson').val();
            var checkin = $('#checkin').val();
            var checkout = $('#checkout').val();
            var night = $('#numnight').val();
            var child = $('#numchild').val();
            var propid = $('#propid').val();
            var markup = [];
            $("input[name='markup[]']").each(function(i) {
                markup[i] = $(this).val();
            });

            var expedia = $('#expedia').val();
            var hotel = $('#hotelcom').val();
            if (person != '' && checkin != '' && checkout != '' && night != '' && child != '' && propid != '') {
                var checkindate = checkin.split('-');
                var checkoutdate = checkout.split('-');

                checkindate = new Date(checkindate[2], checkindate[1], checkindate[0]);
                checkoutdate = new Date(checkoutdate[2], checkoutdate[1], checkoutdate[0]);
                if (checkindate > checkoutdate) {
                    alert("Checkout date should be greater than checkin date");
                } else {
                    jQuery('.priceinfo').html('<span class="loadclass">Loading...</span>');
					$('.loadprice').show();
					$('.priceothers').hide();
                    ajxCall(checkin, checkout, person, child, propid, markup);
                }

            }
        });

        $('#submitbtn').click(function() {
            var person = $('#numperson').val();
            var checkin = $('#checkin').val();
            var checkout = $('#checkout').val();
            var night = $('#numnight').val();
            var child = $('#numchild').val();
            var propid = $('#propid').val();
            var roomid = $('#roomid').val();
            var refid = $('#refid').val();
            var roomtext = '';
            if (roomid) {
                roomtext = '&roomid=' + roomid;
            }
            var reftext = '';
            if (refid) {
                reftext = '&referer=' + refid;
            }
            var url = 'https://book.halu.travel/booking.php?propid=' + propid + '&checkin=' + checkin + '&checkout=' + checkout + '&numadult=' + person + '&numchild=' + child + roomtext + reftext;
            $(location).attr('href', url);
        });
        
        $('#openpop').click(function() {
            var disabledDays;
            var roomid = $('#roomid').val();
            var apikey = $('#apikey').val();
            var propkey = $('#propkey').val();
            if (roomid) {
                $.ajax({
                    type: "POST",
                    url: "/wp-admin/admin-ajax.php",
                    data: {
                        action: 'get_halu_blocked_dates',
                        roomId: roomid,
                        apiKey: apikey,
                        propKey: propkey
                    },
                    dataType: 'json',
                    success: function(response) {
                        if (response.status == 200) {
                            disabledDays = response.response;
                        }
                    },
                });
            }
            // $("#checkin").datepicker({
            //     dateFormat: "dd-mm-yy",
            //     minDate: new Date(),
            //     beforeShowDay: function(date) {
            //         var day = date.getDay();
            //         var string = jQuery.datepicker.formatDate('dd-mm-yy', date);
            //         var isDisabled = ($.inArray(string, disabledDays) != -1);

            //         //day != 0 disables all Sundays
            //         return [!isDisabled];

            //     },
            //     onSelect: function(date, i) {
            //         var dateAr = date.split('-');
            //         var string = dateAr[2] + '-' + dateAr[1] + '-' + dateAr[0]; //Change Fornat
            //         var selectedDate = new Date(string);
            //         var msecsInADay = 86400000;
            //         var endDate = new Date(selectedDate.getTime() + msecsInADay);
            //         //Set Minimum Date of EndDatePicker After Selected Date of StartDatePicker
            //         $("#checkout").datepicker("option", "minDate", endDate);
            //         if (date !== i.lastVal) {
            //             $(this).change();
            //         }

            //     }
            // });
            // $("#checkout").datepicker({
            //     dateFormat: "dd-mm-yy",
            //     minDate: new Date(),
            //     beforeShowDay: function(date) {
            //         var day = date.getDay();
            //         var string = jQuery.datepicker.formatDate('dd-mm-yy', date);
            //         var isDisabled = ($.inArray(string, disabledDays) != -1);

            //         //day != 0 disables all Sundays
            //         return [!isDisabled];

            //     },
            //     onSelect: function(d, i) {
            //         if (d !== i.lastVal) {
            //             $(this).change();
            //         }
            //     }

            // });
              $("#checkin").flatpickr({
					defaultDate: "today",
                    minDate: "today",
                    dateFormat: "Y-m-d",
					altInput: true,
   					altFormat:"d-m-y",
					onChange: function(selectedDates, dateStr, instance) {
						//var dateAr = dateStr.split('-');
						//var string = dateAr[2] + '-' + dateAr[1] + '-' + dateAr[0]; //Change Fornat
						var selectedDate = new Date(dateStr);
						var msecsInADay = 86400000;
						var endDate = new Date(selectedDate.getTime() + msecsInADay);
						$("#checkout").flatpickr({
							defaultDate: endDate,
							minDate: endDate,
							dateFormat: "Y-m-d",
							altInput: true,
							altFormat:"d-m-y",
						});
						const fp = document.querySelector("#checkout")._flatpickr;
						fp.toggle();

					},
                });
                $("#checkout").flatpickr({
					defaultDate: new Date().fp_incr(1),
                    minDate: new Date().fp_incr(1),
                    dateFormat: "Y-m-d",
					altInput: true,
   					altFormat:"d-m-y",
                });

            $('.bookingcontainer').show();
            $('body').addClass('haluwidgetopen');
            var person = $('#numperson').val();
            var checkin = $('#checkin').val();
            var checkout = $('#checkout').val();
            var night = $('#numnight').val();
            var child = $('#numchild').val();
            var propid = $('#propid').val();
            var trydays = $('#trydays').val();
            var markup = [];
            $("input[name='markup[]']").each(function(i) {
                markup[i] = $(this).val();
            });

            var expedia = $('#expedia').val();
            var hotel = $('#hotelcom').val();
            if (person != '' && checkin != '' && checkout != '' && night != '' && child != '' && propid != '') {
                var checkindate = checkin.split('-');
                var checkoutdate = checkout.split('-');
                var checkindate = checkin.split('-');
                var checkid = new Date(checkindate[2], checkindate[1] - 1, checkindate[0]);
                var checkod = new Date(checkoutdate[2], checkoutdate[1] - 1, checkoutdate[0]);
                if (Date.parse(checkid) > Date.parse(checkod)) {
                    alert("Checkout date should be greater than checkin date");
                } else {
                    jQuery('.priceinfo').html('<span class="loadclass">Loading...</span>');
                    ajxCall_start(checkin, checkout, person, child, propid, markup, trydays);
                }

            }
        })
        startboxupdate();
        function startboxupdate(){
                var disabledDays;
                var roomid = $('#roomid').val();
                var apikey = $('#apikey').val();
                var propkey = $('#propkey').val();
                if (roomid) {
                    $.ajax({
                        type: "POST",
                        url: "/wp-admin/admin-ajax.php",
                        data: {
                            action: 'get_halu_blocked_dates',
                            roomId: roomid,
                            apiKey: apikey,
                            propKey: propkey
                        },
                        dataType: 'json',
                        success: function(response) {
                            if (response.status == 200) {
                                disabledDays = response.response;
                            }
                        },
                    });
                }
			// $("#checkin").datepicker({
            //     dateFormat: "dd-mm-yy",
            //     minDate: new Date(),
            //     beforeShowDay: function(date) {
            //         var day = date.getDay();
            //         var string = jQuery.datepicker.formatDate('dd-mm-yy', date);
            //         var isDisabled = ($.inArray(string, disabledDays) != -1);

            //         //day != 0 disables all Sundays
            //         return [!isDisabled];

            //     },
            //     onSelect: function(date, i) {
            //         var dateAr = date.split('-');
            //         var string = dateAr[2] + '-' + dateAr[1] + '-' + dateAr[0]; //Change Fornat
            //         var selectedDate = new Date(string);
            //         var msecsInADay = 86400000;
            //         var endDate = new Date(selectedDate.getTime() + msecsInADay);
            //         //Set Minimum Date of EndDatePicker After Selected Date of StartDatePicker
            //         $("#checkout").datepicker("option", "minDate", endDate);
            //         if (date !== i.lastVal) {
            //             $(this).change();
            //         }

            //     }
            // });
            // $("#checkout").datepicker({
            //     dateFormat: "dd-mm-yy",
            //     minDate: new Date(),
            //     beforeShowDay: function(date) {
            //         var day = date.getDay();
            //         var string = jQuery.datepicker.formatDate('dd-mm-yy', date);
            //         var isDisabled = ($.inArray(string, disabledDays) != -1);

            //         //day != 0 disables all Sundays
            //         return [!isDisabled];

            //     },
            //     onSelect: function(d, i) {
            //         if (d !== i.lastVal) {
            //             $(this).change();
            //         }
            //     }

            // });
                $("#checkin").flatpickr({
					defaultDate: "today",
                    minDate: "today",
                    dateFormat: "Y-m-d",
					altInput: true,
   					altFormat:"d-m-y",
					onChange: function(selectedDates, dateStr, instance) {
						//var dateAr = dateStr.split('-');
						//var string = dateAr[2] + '-' + dateAr[1] + '-' + dateAr[0]; //Change Fornat
						var selectedDate = new Date(dateStr);
						var msecsInADay = 86400000;
						var endDate = new Date(selectedDate.getTime() + msecsInADay);
						console.log(endDate);
						 $("#checkout").flatpickr({
							defaultDate: endDate,
							minDate: endDate,
							dateFormat: "Y-m-d",
							altInput: true,
							altFormat:"d-m-y",
						});
						const fp = document.querySelector("#checkout")._flatpickr;
						fp.toggle();
					},
                });
                $("#checkout").flatpickr({
					defaultDate: new Date().fp_incr(1),
                    minDate: new Date().fp_incr(1),
                    dateFormat: "Y-m-d",
					altInput: true,
   					altFormat:"d-m-y",
                });
                var person = $('#numperson').val();
                var checkin = $('#checkin').val();
                var checkout = $('#checkout').val();
                var night = $('#numnight').val();
                var child = $('#numchild').val();
                var propid = $('#propid').val();
                var trydays = $('#trydays').val();
                var markup = [];
                $("input[name='markup[]']").each(function(i) {
                    markup[i] = $(this).val();
                });
                if (person != '' && checkin != '' && checkout != '' && night != '' && child != '' && propid != '') {
                    var checkindate = checkin.split('-');
                    var checkoutdate = checkout.split('-');
                    var checkindate = checkin.split('-');
                    var checkid = new Date(checkindate[2], checkindate[1] - 1, checkindate[0]);
                    var checkod = new Date(checkoutdate[2], checkoutdate[1] - 1, checkoutdate[0]);
                    if (Date.parse(checkid) > Date.parse(checkod)) {
                        alert("Checkout date should be greater than checkin date");
                    } else {
                        jQuery('.priceinfo').html('<span class="loadclass">Loading...</span>');
                        ajxCall_start(checkin, checkout, person, child, propid, markup, trydays);
                    }
    
                }
        }
        $('#closepop').click(function() {
            $('.bookingcontainer').hide();
            $('.halustarter').remove();

            $('body').removeClass('haluwidgetopen');
        })
        $('#openmainpop').click(function() {
            $('.halustarter').remove();
            $('.bookingcontainer,#openpop').show();
            $('body').addClass('haluwidgetopen');
        });
        $('#closepopstart').click(function() {
            $('.halustarter').remove();
            $('#openpop').show();
        });
        $('#submitbtnstart').click(function() {
            $('#submitbtn').click();
        })
    })

    /*Function to get Price on Change*/
    function ajxCall(checkin, checkout, person, child, propid, markup) {
        $.ajax({
            type: "POST",
            url: "/wp-admin/admin-ajax.php",
            data: {
                action: 'get_widget_price',
                checkIn: checkin,
                checkOut: checkout,
                numAdult: person,
                numChild: child,
                propId: propid
            },
            dataType: 'json',
            success: function(response) {
                if (response.status == 200) {
                    if (response.price != null) {
                        var i;
                        for (i = 0; i < markup.length; ++i) {
                            var price = response.price * markup[i];
                            var price = Math.round(price.toFixed(2));
                            $('#markupprice' + i).html('€ ' + price);
                            // do something with MARKUPS
                        }
                        var checkinar = response.check_in.split('-');
                        var checkin = checkinar[2] + '-' + checkinar[1] + '-' + checkinar[0];
                        var checkoutar = response.check_out.split('-');
                        var checkout = checkoutar[2] + '-' + checkoutar[1] + '-' + checkoutar[0];
                        var date1 = new Date(checkin);
                        var date2 = new Date(checkout);
                        var timeDiff = Math.abs(date2.getTime() - date1.getTime());
                        var numberOfNights = Math.ceil(timeDiff / (1000 * 3600 * 24));

                        var nighttext = 'Night';
                        if (numberOfNights > 1) {
                            nighttext = 'Nights';
                        }
                        var persontext = 'Adult';
                        if (person > 1) {
                            persontext = 'Adults';
                        }
                        $('#hideotherbooking,.priceothers').show();
                        $('#otherline').show();
                        $('#price').html('€ ' + response.price);
                        $('.peopleinfo').html('<span>' + numberOfNights + ' ' + nighttext + '</span> <span id="adultperson">' + person + ' ' + persontext + '</span>');
						$('.loadprice').hide();
                    } else {
						
                        $('#price').html('NA');
                        $('#hideotherbooking').hide();
                        $('#otherline').hide();

                    }
                }
            },
        });
    }


    /*Function to get Price on Start*/
    function ajxCall_start(checkin, checkout, person, child, propid, markup, trydays) {
        $.ajax({
            type: "POST",
            url: "/wp-admin/admin-ajax.php",
            data: {
                action: 'get_widget_price_start',
                checkIn: checkin,
                checkOut: checkout,
                numAdult: person,
                numChild: child,
                propId: propid,
                tryDays: trydays
            },
            dataType: 'json',
            success: function(response) {
                if (response.status == 200) {
                    if (response.price != null && response.price != 'NA') {
                        var i;
                        for (i = 0; i < markup.length; ++i) {
                            var price = response.price * markup[i];
                            var price = Math.round(price.toFixed(2));
                            $('#markupprice' + i).html('€ ' + price);
                            $('#smarkupprice' + i).html('€ ' + price);
                            // do something with MARKUPS

                        }

                        var checkinar = response.check_in.split('-');
                        var checkin = checkinar[2] + '-' + checkinar[1] + '-' + checkinar[0];
                        var checkoutar = response.check_out.split('-');
                        var checkout = checkoutar[2] + '-' + checkoutar[1] + '-' + checkoutar[0];
                        var date1 = new Date(checkin);
                        var date2 = new Date(checkout);
                        var timeDiff = Math.abs(date2.getTime() - date1.getTime());
                        var numberOfNights = Math.ceil(timeDiff / (1000 * 3600 * 24));
                        var nighttext = 'Night';
                        if (numberOfNights > 1) {
                            nighttext = 'Nights';
                        }
                        var persontext = 'Adult';
                        if (person > 1) {
                            persontext = 'Adults';
                        }
                        $('#checkin').val(response.check_in);
                        $('#checkout').val(response.check_out);
                        $('#hideotherbooking').show();
                        $('#otherline').show();
                        $('#price,#startingprice').html('€ ' + response.price);
                        $('.peopleinfo').html('<span>' + numberOfNights + ' ' + nighttext + '</span> <span id="adultperson">' + person + ' ' + persontext + '</span>');
                        $('.loadprice').hide(); 
						 $('#welcomenights').html('For '+numberOfNights+' '+nighttext); 
                        $('.halustarter,.priceothers').show();
                    } else {
                       
                        $('#price').html('NA');
                        $('#hideotherbooking').hide();
                        $('#otherline').hide();
                        $('#openpop').show();

                    }
                }
               
            },
        });
    }
})(jQuery);
document.addEventListener('DOMContentLoaded', function() {
	var inputs = document.getElementsByClassName('input-number-wrapper')
	
	function incInputNumber(input, step) {
		var val = +input.value
		if (isNaN(val)) val = 0
		val += step
		input.value = val > 0 ? val: 0
		// If you need to change the input value in the DOM :
		// var newValue = val > 0 ? val : 0;
		// input.setAttribute("value", newValue);
	}
	
	Array.prototype.forEach.call(inputs, function(el) {
		var input = el.getElementsByTagName('input')[0]
		
		el.getElementsByClassName('increase')[0].addEventListener('click', function() { incInputNumber(input, 1); jQuery('#numchild').change(); })
		el.getElementsByClassName('decrease')[0].addEventListener('click', function() { incInputNumber(input, -1); jQuery('#numchild').change(); })
	})
});