const urlParams = new URLSearchParams(window.location.search);
const level = urlParams.get('level');

if (level) {
    var url = 'https://' + window.location.host + '/general-information/';
    setTimeout(function() {
        jQuery('.pmpro_actions_nav a').prop('href', url);
    }, 1000);
}



document.addEventListener("DOMContentLoaded", function() {
    const tabHeaders = document.querySelectorAll(".notification_section_tab_header .notification_section_title");
    const tabContents = document.querySelectorAll(".notification_section_tab_body .notification_section_description");

    function showTab(tabIndex) {
        for (let i = 0; i < tabHeaders.length; i++) {
            if (i === tabIndex) {
                tabHeaders[i].classList.add("notification_tab_active");
                tabContents[i].style.display = "block";
            } else {
                tabHeaders[i].classList.remove("notification_tab_active");
                tabContents[i].style.display = "none";
            }
        }
    }
    showTab(0);
    tabHeaders.forEach(function(tabHeader, index) {
        tabHeader.addEventListener("click", function() {
            showTab(index);
        });
    });
});



// Range Slider start
/*var rangeOne = document.querySelector('input[name="rangeOne"]'),

    rangeTwo = document.querySelector('input[name="rangeTwo"]'),

    outputOne = document.querySelector('.outputOne'),

    outputTwo = document.querySelector('.outputTwo'),

    inclRange = document.querySelector('.incl-range'),

    updateView = function() {

        if (this.getAttribute('name') === 'rangeOne') {

            outputOne.innerHTML = this.value;
            outputOne.setAttribute("data-rangeone", this.value);
        } else {

            outputTwo.innerHTML = this.value;
            outputTwo.setAttribute("data-rangeTwo", this.value);
        }

        if (parseInt(rangeOne.value) > parseInt(rangeTwo.value)) {

            inclRange.style.width = (rangeOne.value - rangeTwo.value) / this.getAttribute('max') * 100 + '%';

            inclRange.style.left = rangeTwo.value / this.getAttribute('max') * 100 + '%';

        } else {

            inclRange.style.width = (rangeTwo.value - rangeOne.value) / this.getAttribute('max') * 100 + '%';

            inclRange.style.left = rangeOne.value / this.getAttribute('max') * 100 + '%';

        }

    };*/


const onInput = (parent, e) => {
  const slides = parent.querySelectorAll('input');
  const min = parseFloat(slides[0].min);
  const max = parseFloat(slides[0].max);

  let slide1 = parseFloat(slides[0].value);
  let slide2 = parseFloat(slides[1].value);

  const percentageMin = (slide1 / (max - min)) * 100;
  const percentageMax = (slide2 / (max - min)) * 100;

  parent.style.setProperty('--range-slider-value-low', percentageMin);
  parent.style.setProperty('--range-slider-value-high', percentageMax);

  if (slide1 > slide2) {
    const tmp = slide2;
    slide2 = slide1;
    slide1 = tmp;

    if (e?.currentTarget === slides[0]) {
      slides[0].insertAdjacentElement('beforebegin', slides[1]);
    } else {
      slides[1].insertAdjacentElement('afterend', slides[0]);
    }
  }
  jQuery('.range-slider__display').empty();
//   parent.querySelector('.range-slider__display').setAttribute('data-low', slide1);
//   parent.querySelector('.range-slider__display').setAttribute('data-high', slide2);
  
  jQuery('#getRangeOne').val(slide1);
  jQuery('#getRangeTwo').val(slide2);
  
  var set_range = slide1+' km - '+slide2+' km';
  
  jQuery('.range-slider__display').append(set_range);
}

addEventListener('DOMContentLoaded', (event) => {
  document.querySelectorAll('.range-slider')
   .forEach(range => range.querySelectorAll('input')
      .forEach((input) => {
      if (input.type === 'range') {
        input.oninput = (e) => onInput(range, e);
        onInput(range);
      }
   }))
});



// document.addEventListener('DOMContentLoaded', function() {

//     updateView.call(rangeOne);

//     updateView.call(rangeTwo);

//     $('input[type="range"]').on('mouseup', function() {

//         this.blur();

//     }).on('mousedown input', function() {

//         updateView.call(this);

//     });

// });

// Range Slider End





jQuery(document).ready(function() {

    jQuery('#gly-remove-btn').click(function() {
        console.log('test');
        var wrapperThumb = $(this).closest('.wrapper-thumb');
        var dataId = wrapperThumb.find('.img-preview-thumb').data('id');
        var confirmed = confirm("Are you sure you want to Delete Image");
        if (confirmed) {
            jQuery.ajax({
                type: "POST",
                url: "/wp-admin/admin-ajax.php",
                data: {
                    action: 'delete_gallery_image',
                    id: dataId,

                },
                success: function(data) {
                    console.log(data);
                    $('.img-preview-thumb[data-id="' + dataId + '"]').parent().remove();
                }
            });
        }
    })


    // jQuery('.remove-btn').click(function() {
    //     var wrapperThumb = $(this).closest('.wrapper-thumb');
    //     var dataId = wrapperThumb.data('id'); // Updated to use data-id directly from wrapperThumb

    //     var confirmed = confirm("Are you sure you want to Delete Image");
    //     if (confirmed) {
    //         jQuery.ajax({
    //             type: "POST",
    //             url: "/wp-admin/admin-ajax.php",
    //             data: {
    //                 action: 'legal_documents_image',
    //                 id: dataId,
    //             },
    //             success: function(data) {
    //                 console.log(data);
    //                 $('.wrapper-thumb[data-id="' + dataId + '"]').remove(); // Updated to remove the entire wrapper-thumb
    //             }
    //         });
    //     }
    // });

    //Remove Icon mobile View

    jQuery('.mysidebar').click(function() {
        jQuery('.profile-sidebar').addClass('show');
    })


    jQuery('.sub-menu > a').click(function() {
        // e.preventDefault();
        jQuery('.sub-menu').not(this).removeClass('sub-menu-active');
        jQuery(this).toggleClass('sub-menu-active');
        jQuery('.ol-open').toggle();
    });


    // Seach JS Start
    jQuery('.hide_btn').hide();
    jQuery('#myButton').click(function() {
        jQuery('body').addClass('map_view');
        jQuery('.hide_btn').show();
    });

    jQuery('.gallery').click(function() {
        jQuery('body').removeClass('map_view');
        jQuery('.hide_btn').hide();
    })

    jQuery('#filterbtn').click(function() {
        jQuery('html').addClass('sidebar_open');
    });

    jQuery("#close_sidebar").click(function() {
        jQuery("html").removeClass("sidebar_open");
    });

    setTimeout(() => {
        jQuery(".search_btn").click(function() {
            jQuery("html").removeClass("sidebar_open");
        });
    }, 10);

    jQuery('#page_Therapies').click(function() {
        location.reload();
    })

    jQuery('#home').click(function() {
        var base_url = window.location.origin;
        window.location.href = base_url;
    })

    jQuery('#Massage').click(function() {
            var base_url = window.location.origin;
            window.location.href = base_url + '/massages';
        })
        // Seach JS END 

    jQuery('.single_notification').click(function() {
        var confirmed = confirm("Are you sure you want to Delete Notification");
        if (confirmed) {
            jQuery.ajax({
                type: "POST",
                url: "/wp-admin/admin-ajax.php",
                data: {
                    action: 'delete_single_notification',
                    id: jQuery(this).data('not_id'),
                    table_name: jQuery(this).data('table_name'),

                },
                success: function(data) {
                    console.log(data);
                    location.reload();
                }
            });
        }
    })

    jQuery('#clear_notification').click(function() {
        var confirmed = confirm("Are you sure you want to Delete All Notification");
        if (confirmed) {
            jQuery.ajax({
                type: "POST",
                url: "/wp-admin/admin-ajax.php",
                data: {
                    action: 'delete_all_notification',
                    user_id: jQuery(this).data('user_id'),

                },
                success: function(data) {
                    console.log(data);
                    location.reload();
                    jQuery('#notification_bell').click();
                }
            });
        }
    })

    jQuery('.clear_btn').click(function() {
        var confirmed = confirm("Are you sure you want to Delete All Notification");
        if (confirmed) {
            jQuery.ajax({
                type: "POST",
                url: "/wp-admin/admin-ajax.php",
                data: {
                    action: 'delete_all_notification',
                    user_id: jQuery(this).data('user_id'),

                },
                success: function(data) {
                    console.log(data);
                    location.reload();
                }
            });
        }
    })

    // notification start
    jQuery('#notification_bell').click(function() {
        jQuery('.notification_section_wrapper').toggle();
    });


    // Notification end

    //DropDown input - select
    // jQuery('.t-dropdown-input').on('click', function() {
    //   jQuery(this).parent().next().slideDown('fast');
    // });

    jQuery('.t-select-btn').on('click', function() {
        jQuery('.t-dropdown-list').slideUp('fast');

        if (!jQuery(this).prev().attr('disabled')) {
            jQuery(this).prev().trigger('click');
        }
    });

    jQuery('.t-dropdown-input').width(jQuery('.t-dropdown-select').width() - jQuery('.t-select-btn').width() - 13);

    jQuery('.t-dropdown-list').width(jQuery('.t-dropdown-select').width());

    // jQuery('.t-dropdown-input').val('');

    jQuery(document).on('click', function(event) {
        if (jQuery(event.target).closest(".t-dropdown-input, .t-select-btn").length)
            return;
        jQuery('.t-dropdown-list').slideUp('fast');
        event.stopPropagation();
    });
    // END //


    jQuery(document).on('click', 'li.t-dropdown-item', function() {
        var text = jQuery(this).html();
        jQuery(this).parent().prev().find('.t-dropdown-input').val(text);
        jQuery('.t-dropdown-list').slideUp('fast');
    });


    //keyword
    jQuery('.t-select-btn').on('click', function() {
        jQuery('.t-dropdown-list-keyword').slideUp('fast');

        if (!jQuery(this).prev().attr('disabled')) {
            jQuery(this).prev().trigger('click');
        }
    });

    jQuery('.t-dropdown-input').width(jQuery('.t-dropdown-select').width() - jQuery('.t-select-btn').width() - 13);

    jQuery('.t-dropdown-list-keyword').width(jQuery('.t-dropdown-select').width());

    // jQuery('.t-dropdown-input').val('');

    jQuery(document).on('click', function(event) {
        if (jQuery(event.target).closest(".t-dropdown-input, .t-select-btn").length)
            return;
        jQuery('.t-dropdown-list-keyword').slideUp('fast');
        event.stopPropagation();
    });
    // END //


    jQuery(document).on('click', 'li.t-dropdown-item', function() {
        var text = jQuery(this).html();
        jQuery(this).parent().prev().find('.t-dropdown-input').val(text);
        jQuery('.t-dropdown-list-keyword').slideUp('fast');
    });



    // setTimeout(function() {
        // jQuery('#keyword_search').on('input', function() {
        //     alert('Helo');
        //     console.log('Click');
        //     var keyword_val = jQuery(this).val();
        //     if (keyword_val.length == 3) {

        //         var jsonUrl = <?php site_url('/wp-content/themes/massagemybody-child/assets/js/data.json') ?>;
        //         jQuery.getJSON(jsonUrl, function(data) {
        //             var matchingData = data.filter(item => item.toLowerCase().includes(keyword_val));
        //             jQuery('.t-dropdown-list-keyword').empty();
        //             var $list = jQuery(".t-dropdown-list-keyword");
        //             jQuery.each(matchingData, function(index, item) {
        //                 var $li = jQuery('<li class="t-dropdown-item">').text(item);
        //                 $list.append($li);
        //             });

        //             jQuery('.t-dropdown-list-keyword').css('display', 'block');
        //             jQuery(this).parent().next().slideDown('fast');

        //             console.log(matchingData);
        //         });

        //     }
        // })
    // })

   jQuery('#postcodes_enter').on('keyup', function() {
        
        console.log('cjeckong');
        var post_code = jQuery(this).val().toUpperCase();
        jQuery('.t-dropdown-list').empty();
        var $list = jQuery(".t-dropdown-list");
        $list.empty();
        console.log(postcoe);
        var matchingData = postcoe.filter(item => {
            if (item.indexOf(post_code) != -1) {
                var $li = jQuery('<li class="t-dropdown-item">').text(item);
                $list.append($li);
                return item;
            }
        });
        jQuery('.t-dropdown-list').css('display', 'block');
        jQuery(this).parent().next().slideDown('fast');
    });


    jQuery('#defaultModel').hide();
    jQuery('#parent-radio-check input[type="radio"]').click(function() {
        var inputValue = jQuery(this).attr("value");
        var targetBox = jQuery("." + inputValue);
        jQuery(".main-form").not(targetBox).hide();
        jQuery(targetBox).show();
        //jQuery(".service-reg").removeClass('show-img');
        if (inputValue == 'massaeur') {
            jQuery(".service-reg").addClass('show-img');
            jQuery(".client-reg").addClass('remove-img');

        } else {
            jQuery(".service-reg").removeClass('show-img');
            jQuery(".client-reg").removeClass('remove-img');
        }
    });

    jQuery("#ProviderRegisterForm").hide();
    jQuery("#client").prop("checked", true);
    // $("div.desc").hide();
    jQuery("#client").click(function() {
        //  var test = $(this).val();
        jQuery("#ProviderLoginForm").show();
        jQuery("#ProviderRegisterForm").hide();
        //jQuery("#" + test).show();
    });
    jQuery("#provider").click(function() {
        //  var test = $(this).val();
        jQuery("#ProviderLoginForm").hide();
        jQuery("#ProviderRegisterForm").show();
        //jQuery("#" + test).show();
    });

    // Search form start
    // jQuery(document).on("click",".search_suburb", function() {
    // jQuery.ajax({
    //             url: '<?php echo admin_url('admin-ajax.php'); ?>',
    //             type: 'post',
    //             data:{ 
    //                 action: 'data_fetch', 
    //                 keyword: jQuery('#keyword').val(),
    //                 location: jQuery('#location').val(),
    //                 category: jQuery('#category').val()
    //             },
    //             success: function(data) {
    //                 jQuery('#datafetch').html( data );
    //             }
    //         });

    //     });

    // home page therapist listing slider start
    function custom_slider_therapist() {
        $('.custom-slider-col').slick({
            dots: true,
            autoplay: true,
            draggable: true
        });
    }
    // home page therapist listing slider End
    // Call home page therapist listing slider
    custom_slider_therapist();

    // Search filter Ajax Start
    var filter_res = {};
    jQuery("#sortby").change(function() {

        filter_res.sortby = jQuery(this).val();
        var short = jQuery(this).val();
        var order = 'asc';
        if (short == 'top_price') {
            var dataval = 'price';
        } else if (short == 'most_viewed') {
            var dataval = 'count_view';
            order = 'desc';
        } else if (short == 'top_rated') {
            var dataval = 'rated';
        }
        sortDivsByAttr(dataval, order);
    });

    function sortDivsByAttr(attr, order) {
        // Select all the div elements with data-price attribute
        var $divs = $('div[data-' + attr + ']');

        // Sort the div elements based on their data-price attribute
        $divs.sort(function(a, b) {
            var dataA = parseInt($(a).data(attr));
            var dataB = parseInt($(b).data(attr));
            return order === 'asc' ? dataA - dataB : dataB - dataA;
        });

        // Append the sorted div elements to their parent container
        $divs.appendTo($divs.parent());
    }


   
    jQuery("#post-code").keyup(function() {
        if(jQuery( this ).val().length >= 3 ){
        
        //filter_res.postcode = jQuery(this).val();
        
         var post_code  = jQuery(this).val();
        getlatlong(post_code);
        
        }
    });
    
    
    const post_code = urlParams.get('suburb_postcode'); 
    // console.log(post_code + ' ' + post_code);
  
    if(urlParams.has('s')){
      var range = 333;
      var min_range = 0;
      var max_range = 30;
     
      
      if(urlParams.get('s') != ''){
          
          filter_res.searchkey = urlParams.get('s');
     }
     
       getlatlong(post_code);
       
      //search_filters(filter_res);
      
   }
      

    
    function getlatlong(post_code){
           jQuery.ajax({
            url: '/wp-admin/admin-ajax.php',
            type: 'POST',
            data: {
                action: 'get_lat_long_by_postcode', // AJAX action name
                postcode: post_code
            },
            success: function(response) {
                
                
                if (response.error) {
                    console.log('Error:', response.error);
                } else {
                    console.log('Latitude:', response.latitude);
                    console.log('Longitude:', response.longitude);
                }
                
                 var latitude = response.latitude;
                var longitude = response.longitude;
                
                 filter_res.latitude = latitude;
                 filter_res.longitude = longitude;
                 filter_res.range = range;
                 filter_res.min_range = min_range;
                 filter_res.max_range = max_range;
                 
                filter_res.post_code = post_code;
                
                console.log(response);
                search_range(filter_res);
                
                console.log(filter_res);
                
                
            },
            error: function(xhr, status, error) {
                console.log('AJAX Error:', error);
            }
        });
        
        
        
        //search_filters(filter_res);
        
    }
    
    


    jQuery("#searh-key").keyup(function() {
        filter_res.searchkey = jQuery(this).val();
        //search_range(filter_res);
        search_filters(filter_res);
    });


    /* Range Find data Start */

    jQuery('input[name="rangeTwo"],input[name="rangeOne"]').change(function() {
        // var range = jQuery('.range-slider__display').attr('data-high');
        var range = jQuery('#getRangeTwo').val();
        filter_res.range = range;
        // console.log(range);
        var min_range = jQuery('#getRangeOne').val();
        var max_range = jQuery('#getRangeTwo').val();
        filter_res.min_range = min_range;
        filter_res.max_range = max_range;
            
         
        var post_code = jQuery('#post-code').val();
        
        
        if(post_code == ''){
        
        if ("geolocation" in navigator) {
            navigator.geolocation.getCurrentPosition(function(position) {
                // Get latitude and longitude from the position object
                var latitude = position.coords.latitude;
                var longitude = position.coords.longitude;

                filter_res.latitude = latitude;
                filter_res.longitude = longitude;
               
                filter_res.post_code = post_code;
               search_range(filter_res);
                console.log(filter_res);
            });
        }
        }else{
            
            search_range(filter_res);
        }
        
         
        
        
    })
    
    
    // jQuery('input[name="rangeOne"]').change(function() {
    //         // var range = jQuery('.range-slider__display').attr('data-low');
    //          var range = jQuery('#getRangeOne').val();
    //         console.log(range);
    //         var post_code = jQuery('#post-code').val();
    //         if ("geolocation" in navigator) {
    //             navigator.geolocation.getCurrentPosition(function(position) {
    //                 // Get latitude and longitude from the position object
    //                 var latitude = position.coords.latitude;
    //                 var longitude = position.coords.longitude;

    //                 filter_res.latitude = latitude;
    //                 filter_res.longitude = longitude;
    //                 filter_res.range = range;
    //                 filter_res.post_code = post_code;
    //                 search_range(filter_res);
    //                 console.log(filter_res);
    //             });
    //         }
    //     })
        /* Range Find data end */



    jQuery('#radio_business .inner_label').change(function() {
        filter_res.massage_service = jQuery("input[name='group1']:checked").val();
        //console.log(massage_service);
        // search_filters(filter_res);
        search_range(filter_res);
    });

    jQuery('.massage_gender .inner_label').change(function() {
        filter_res.massage_gender = jQuery("input[name='group2']:checked").val();
        // search_filters(filter_res);
        
        search_range(filter_res);
        //console.log(massage_gender);
    });

    jQuery(".independent_massage_therapist_div .inner_label").click(function() {
        //Create an Array.
        var selected = new Array();

        //Reference the CheckBoxes and insert the checked CheckBox value in Array.
        jQuery(".independent_massage_therapist_div .inner_label input[type=checkbox]:checked").each(function() {
            selected.push(this.value);
        });

        //Display the selected CheckBox values.
        // if (selected.length > 0) {
        filter_res.sevice_provider = selected.join(",");
        // search_filters(filter_res);
        
        search_range(filter_res);
        // }
    });

    jQuery("#relaxation_massage .inner_label").click(function() {
        //Create an Array.
        var selected = new Array();

        //Reference the CheckBoxes and insert the checked CheckBox value in Array.
        jQuery("#relaxation_massage .inner_label input[type=checkbox]:checked").each(function() {
            selected.push(this.value);
        });

        //Display the selected CheckBox values.
        // if (selected.length > 0) {
        filter_res.relaxation_massage = selected.join(",");
        // search_filters(filter_res);
        
        search_range(filter_res);
        
        // }
    });

    jQuery("#therapist_massage .inner_label").click(function() {
        //Create an Array.
        var selected = new Array();

        //Reference the CheckBoxes and insert the checked CheckBox value in Array.
        jQuery("#therapist_massage .inner_label input[type=checkbox]:checked").each(function() {
            selected.push(this.value);
        });

        //Display the selected CheckBox values.
        // if (selected.length > 0) {
        filter_res.therapist_massage = selected.join(",");
        
        search_range(filter_res);
        
        // search_filters(filter_res);
        // }
    });

    jQuery("#other_massage .inner_label").click(function() {
        //Create an Array.
        var selected = new Array();

        //Reference the CheckBoxes and insert the checked CheckBox value in Array.
        jQuery("#other_massage .inner_label input[type=checkbox]:checked").each(function() {
            selected.push(this.value);
        });

        //Display the selected CheckBox values.
        // if (selected.length > 0) {
        filter_res.other_massage = selected.join(",");
        // search_filters(filter_res);
        
        search_range(filter_res);
        
        // }
    });
    jQuery('#clear_all_data').click(function() {
        if (confirm("Want to clear?")) {
            /*Clear all input type="text" box*/
            jQuery('.search_box input[type="text"]').val('');
            jQuery('.search_box input[type=checkbox]').prop('checked', false);
            jQuery('.search_box input[name="group2"]').prop('checked', false);
            jQuery('.search_box input[name="group1"]').prop('checked', false);
        }
        filter_res.postcode = "";
        filter_res.other_massage = "";
        filter_res.therapist_massage = "";
        filter_res.relaxation_massage = "";
        filter_res.sevice_provider = "";
        filter_res.massage_gender = "";
        filter_res.searchkey = "";
        filter_res.massage_service = "";
        // search_filters(filter_res);
        search_range(filter_res);
    });

    jQuery(".loding_filter").hide();

    function search_filters(filter_res) {
        // marker.setMap(null);
        jQuery.ajax({
            type: 'POST',
            url: '/wp-admin/admin-ajax.php',
            data: {
                action: 'search_results',
                filter_res: filter_res,
            },
            dataType: 'json',
            cache: 'false',
            async: 'false',
            beforeSend: function() {
                jQuery(".loding_filter").show();
                jQuery("#filter_result").hide();
            },
            success: function(res) {
                
                // alert(res.filtered_data);
                jQuery(".loding_filter").hide();
                jQuery("#filter_result").show();

                jQuery('#total_masseur').empty();
                jQuery('#total_masseur').append(res.data.total_record);

                jQuery("#filter_result").html(res.data.filtered_data);
                custom_slider_therapist();
                initMap();
            },
        });
    }
    // Search filter ajax end


    function search_range(filter_res) {
        
        // jQuery('.preloader').fadeIn('500');
        
        jQuery.ajax({
            type: 'POST',
            url: '/wp-admin/admin-ajax.php',
            data: {
                action: 'search_results_range',
                filter_res: filter_res,

            },
            dataType: 'json',
            cache: 'false',
            async: 'false',
            beforeSend: function() {
                jQuery(".loding_filter").show();
                jQuery("#filter_result").hide();
            },
            success: function(res) {
                // alert(res.filtered_data);
                jQuery(".loding_filter").hide();
                jQuery("#filter_result").show();

                jQuery('#total_masseur').empty();
                jQuery('#total_masseur').append(res.data.total_record);

                jQuery("#filter_result").html(res.data.filtered_data);
                custom_slider_therapist();

                // console.log(res);
                // console.log(searchkey);
                // jQuery('.preloader').fadeOut('500');
            },
        });
    }

    let map;
    let placesService;
    let mapMarker = []; // Store the marker object
    initMap();

    function initMap() {
        // var mapDiv = document.getElementById('map');
        var mapDiv = jQuery('#map').empty();
        // if (mapDiv) {
        //     mapDiv.removeChild(mapDiv); // Remove the map element from the DOM
        // }
        var lat = 40.7128;
        var long = -74.0060;
        // Create a LatLng object for the initial position
        var initialPosition = new google.maps.LatLng(lat, long);

        // Create the map
        map = new google.maps.Map(document.getElementById('map'), {
            // center: initialPosition, // Set the initial position for the map
            zoom: 12
        });

        // Create a PlacesService
        placesService = new google.maps.places.PlacesService(map);

        var markers = [];
        jQuery('.get_lat_log').each(function() {
            var latitude = jQuery(this).attr('data-latitude');
            var longitude = jQuery(this).attr('data-longitude');
            var thep_name = jQuery(this).attr('data-thep_name');
            markers.push({ position: { lat: latitude, lng: longitude }, title: thep_name });
        });

        console.log(markers);

        markers.forEach(function(markerInfo, index) {
            if (index == 0) {
                var newCenter = new google.maps.LatLng(parseFloat(markerInfo.position.lat), parseFloat(markerInfo.position.lng));
                map.setCenter(newCenter);
            }

            var marker = new google.maps.Marker({
                position: { lat: parseFloat(markerInfo.position.lat), lng: parseFloat(markerInfo.position.lng) },
                map: map,
                title: markerInfo.title,
            });
            mapMarker.push(marker);

            var infowindow = new google.maps.InfoWindow({
                content: markerInfo.title, // Display the place name in the info window
            });

            marker.addListener('click', function() {
                infowindow.open(map, marker);
            });
        });

        // Create a draggable marker with the initial position
        // marker = new google.maps.Marker({
        //     map: map,
        //     position: initialPosition, // Set the initial position for the marker
        //     draggable: true // Allow marker to be moved
        // });

        // Add an event listener to update coordinates when the marker is moved
        marker.addListener('dragend', function() {
            const position = marker.getPosition();
            const latitude = position.lat();
            const longitude = position.lng();
            const coordinates = `Latitude: ${latitude}, Longitude: ${longitude}`;
            document.getElementById('coordinates').textContent = coordinates;

        });
    }


    // Function to display a location on the map based on an address
    function geocodeAddress(address) {

        const geocoder = new google.maps.Geocoder();
        geocoder.geocode({ address: address }, function(results, status) {
            if (status === google.maps.GeocoderStatus.OK) {
                const location = results[0].geometry.location;
                const latitude = location.lat();
                const longitude = location.lng();
                const coordinates = `Latitude: ${latitude}, Longitude: ${longitude}`;
                document.getElementById('coordinates').textContent = coordinates;

                // Center the map on the geocoded location and add a marker
                map.setCenter(location);
                marker = new google.maps.Marker({
                    position: location,
                    map: map,
                    title: address,
                    draggable: true // Allow marker to be moved
                });
                marker.addListener('dragend', function() {
                    const position = marker.getPosition();
                    const latitude = position.lat();
                    const longitude = position.lng();
                    const coordinates = `Latitude: ${latitude}, Longitude: ${longitude}`;
                    document.getElementById('coordinates').textContent = coordinates;
                });

            } else {
                alert('Geocode was not successful for the following reason: ' + status);
            }
        });
    }


    document.getElementById('searchAddress').addEventListener('click', function() {
        const address = document.getElementById('addressInput').value;
        if (address) {
            geocodeAddress(address);
        } else {
            alert('Please enter an address to search.');
        }
    });

    // Get the current position of the draggable marker
    document.getElementById('getMarkerPosition').addEventListener('click', function() {
        if (marker) {
            const position = marker.getPosition();
            const latitude = position.lat();
            const longitude = position.lng();
            const coordinates = `Latitude: ${latitude}, Longitude: ${longitude}`;
            document.getElementById('coordinates').textContent = coordinates;
        } else {
            alert('No marker on the map. Please search for an address first.');
        }
    });

});

// Click eye icon on manage password page
function togglePassword(inputId) {
    console.log('test');
    var input = document.getElementById(inputId);
    var icon = input.parentNode.querySelector('.fas');

    if (input.type === "password") {
        input.type = "text";
        icon.classList.remove("fa-eye");
        icon.classList.add("fa-eye-slash");
    } else {
        input.type = "password";
        icon.classList.remove("fa-eye-slash");
        icon.classList.add("fa-eye");
    }
}




// Remove Galler

// $(document).ready(function () {
//     // Attach click event to remove button
//     $('.remove-btn').on('click', function () {
//         // Find the parent wrapper-thumb element
//         var wrapperThumb = $(this).closest('.wrapper-thumb');

//         // Get the data-id attribute value
//         var dataId = wrapperThumb.find('.img-preview-thumb').data('id');

//         // Output the data-id value (optional, for demonstration)
//         console.log('Removing element with data-id:', dataId);

//         // Remove the wrapper-thumb element
//         wrapperThumb.remove();
//     });
// });



// jQuery(document).ready(function ($) {
//   jQuery(document).on('click', '.delete_therapist', function () {
//     alert("hakjfhjakfh");
//     var post_id = $(this).data('post_id_get');
//     console.log(post_id);
//   });
// });