const pathname = window.location.pathname; // Returns path only (/path/example.html)

function diShowHide(id) {
    const elem = document.getElementById(id);
    elem.classList.toggle('d-none');
}

function propInEnsShowHide() {
    diShowHide('propInEns_showHide');
    diShowHide('propInEns_showHide_hid');
    diShowHide('propInEns_showHide_vis');
}

function rcShowMap(){
    $('#gMapsCont').toggleClass('d-none');
    $('#propCont').toggleClass('d-none');
    $('#gMapsBtnLink').toggleClass('d-none');
    $('#propBtnLink').toggleClass('d-none');
}

function loadMelonObj(id, btn_id){
    const iframe = $('#' + id);
    if(iframe.hasClass('d-none')) iframe.removeClass('d-none');
    iframe.attr('src', iframe.data('src'));
    if(btn_id) $('#' + btn_id).hide();
}

function loadIframeSrc(id){
    const iframe = $('#' + id);
    if(iframe.hasClass('d-none')) iframe.removeClass('d-none');
    if(iframe.attr('src') === 'about:blank') iframe.attr('src', iframe.data('src'));
}

async function saveCallBtnClick(btnPosition){
    url = window.location.pathname + window.location.search;
    encodedUrl = encodeURIComponent(url);
    console.log('current url: ', encodedUrl);
    try {
        const response = await fetch(`/save-click?url=${encodeURIComponent(url)}&position=${btnPosition}`, { method: 'POST' });
        if (response.ok) {
          console.log('IP address saved to the database');
        } else {
          console.error('Error saving IP address to the database');
        }
      } catch (error) {
        console.error('Error:', error);
      }
}

// document.addEventListener('DOMContentLoaded', function() {
//     const saveIpButton = document.getElementById('saveIpButton');

//     saveIpButton.addEventListener('click', async function() {
//       try {
//         const response = await fetch('/save-ip', { method: 'POST' });
//         if (response.ok) {
//           console.log('IP address saved to the database');
//         } else {
//           console.error('Error saving IP address to the database');
//         }
//       } catch (error) {
//         console.error('Error:', error);
//       }
//     });
//   });

function diToggleContent(mainId, heightClass, showMoreBtn, hideOne) {
    $('#' + mainId + ' > div.diDropdownContainer').toggleClass(heightClass);
    $('#' + mainId + ' > div.diDropdownGradient').toggleClass('d-none');
    if(showMoreBtn){
        if($('#' + showMoreBtn).hasClass('smClosed')){
            $('#' + showMoreBtn).html('Ascunde');
            $('#' + showMoreBtn).toggleClass('smClosed');
        }
        else{
            $('#' + showMoreBtn).html('Afiseaza');
            $('#' + showMoreBtn).toggleClass('smClosed');
        }
    }
    if(hideOne) $('#' + hideOne).toggleClass('d-none');
}

function mediaPopSwitch(mainId){
    $('div.mediaPopup').addClass('di_d_none');
    $('#' + mainId).removeClass('di_d_none');
    $('span.dip_popup_menu_btn').removeClass('dip_popup_menu_btn_active');
    $('span[data-id="' +  mainId + '"]').addClass('dip_popup_menu_btn_active');

}

function postQuForm(quName, data, recaptchaToken) {
    return new Promise((resolve, reject) => {
        data += '&recaptcha_token=' + recaptchaToken;
        $.post( "../leads/leads-qualif", data)
            .done(function(resp) {
                if(quName == 1) $('#qualifPopFormDiv').attr('data-hash', resp);
                resolve()
            })
    })
}


// function printPropAttr(Def, Val){
//     const html = '<div class="featAttrDef">' + Def + '</div><div class="featAttrVal"><b>' + Val + '</b></div>';
//     return html;
// }

function changeActiveHomeHash(hash){
    $('[data-menu-hash]').removeClass('k_slider_active');
    const hashDiv = $('[data-menu-hash="' + hash + '"]');
    if(hashDiv.hasClass('k_slider_active')) hashDiv.removeClass('k_slider_active');
    else hashDiv.addClass('k_slider_active');
}


//property navigation scroll
$(document).scroll(function() {
    let currYPos = $(this).scrollTop();
    let windowHeight = $(window).height();
    const mblBtmMenu = $('#diMblBMenu');
    const inPagePropNav = $('#inPagePropNav');
    const dipPropNavTop = $('#dipPropNavTop');
    const dipLogoMenu = $('#dipLogoMenu');

    const overview = $('#overview');
    const features = $('#features');
    const price = $('#price');
    const schools = $('#schools');
    const neighbourhood = $('#neighbourhood');
    const supermarkets = $('#supermarkets');

    if (currYPos > windowHeight/2) { //scrolled below 1/2 page
        diScrollSH(mblBtmMenu, 'show'); diScrollSH(dipPropNavTop, 'show');
        // diScrollSH(inPagePropNav, 'hide'); 
        diScrollSH(dipLogoMenu, 'hide');
    } else { //scrolled above 1/2 page
        diScrollSH(mblBtmMenu, 'hide'); diScrollSH(dipPropNavTop, 'hide');
        // diScrollSH(inPagePropNav, 'show'); 
        diScrollSH(dipLogoMenu, 'show');
    }

    if (pathname.indexOf("proprietati") >= 0 || pathname.indexOf("ansambluri") >= 0){
        if(features.length && currYPos < (features.offset().top - 1)) diScrollHorizH('dipPropNavTop', 'overview'); //bold overview
        else if(price.length && currYPos < (price.offset().top - 1)) diScrollHorizH('dipPropNavTop', 'features'); //bold features
        else if(schools.length && currYPos < (schools.offset().top - 1)) diScrollHorizH('dipPropNavTop', 'price'); //bold price
        else if(neighbourhood.length && currYPos < (neighbourhood.offset().top - 1)) diScrollHorizH('dipPropNavTop', 'schools'); //bold schools
        else if(supermarkets.length && currYPos < (supermarkets.offset().top - 1)) diScrollHorizH('dipPropNavTop', 'neighbourhood'); //bold neighbourhood 
        else diScrollHorizH('dipPropNavTop', 'supermarkets'); //bold supermarkets
    }
    // const priceHighlight = $('.rc_price_highlight');
    // const priceHighlightOffset = priceHighlight.offset().top;
    // // const windowHeight = $(window).height();
    // // const scrollTop = $(window).scrollTop();
  
    // if (priceHighlightOffset < (currYPos + windowHeight) && (priceHighlightOffset + priceHighlight.height()) > currYPos) {
    //     priceHighlight.addClass('activehighlight');
    //     console.log('entered viewport');
    // // target element is in the viewport
    // } else {
    //     console.log('not in viewport');
    //     // target element is not in the viewport
    // }

  });

  const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
      if (entry.isIntersecting) {
        //   console.log('entered viewport' + entry);
          console.dir(entry);
          entry.target.classList.add('activehighlight');
          // target element has entered the viewport
      } else {
          // target element has exited the viewport
      }
      });
  });

  const packagesTableObserver = new IntersectionObserver((entry) => {
    console.log(entry[0].target);
    const body = document.querySelector('body');
    if (entry[0].isIntersecting) { // target element has entered the viewport
        console.log('table entered viewport' + entry);
        body.classList.remove('di_o_x_h');
       
    } else { // target element has exited the viewport
        body.classList.add('di_o_x_h');
    }
  });


  
    // const priceHighlight = $('.rc_price_highlight');
    // priceHighlight.forEach((divElement) => {
    //     observer.observe(divElement);
    // });


  function diScrollSH(selector, action){
    if(action === 'show'){
        if (selector.hasClass('di_d_none')) selector.removeClass('di_d_none');
    }else{
        if (!selector.hasClass('di_d_none')) selector.addClass('di_d_none');
    }
  }

  function diScrollHorizH(scrollCont, scrollToItm){
        const scMenuCont= $("#" + scrollCont);
        const scMenuContScroll= scMenuCont.attr('data-scroll');
        const scMenuItm= $("#" + scrollCont + " a[href*='" + scrollToItm + "']");
        if(scMenuContScroll !== scrollToItm || scMenuContScroll == ""){
            $('.dipPropScrollH').removeClass('dipPropScrollHSelected');
            scMenuCont.scrollLeft(scMenuItm.offset().left - scMenuCont.offset().left);
            scMenuCont.attr('data-scroll', scrollToItm);
            $("a[href*='" + scrollToItm + "']").addClass('dipPropScrollHSelected');
        }
  }

  function dipSearch(){
    let searchQuery = $('#searchGridInput').val();
    console.log('search executed');
    window.location.href = "/cautare?locatie=" + searchQuery;
  }

  function dipDDSearch(){
    const searchBar = $('#searchGridBar');
    const width = searchBar.width();
    const height = searchBar.height();
    // const searchBarOffs = searchBar.offset(); 
    const searchBarOffTop = searchBar.position().top; 
    const searchBarOffLeft = searchBar.position().left; 
    // const topDist = searchBarOffs.top + height + 10;
    // const leftDist = searchBarOffs.left;
    const topDist = searchBarOffTop + height + 10;
    const leftDist = searchBarOffLeft;
    const dropDown = $('#searchGridDDRes');

    $('#searchGridDDClose').removeClass('d-none');
    dropDown.removeClass('d-none');
    console.log("width: " + width + " | height: " + height + " | topDist: " + topDist);
    dropDown.css('width', width + "px");
    // dropDown.css('height', "70vh");
    dropDown.css('top', topDist + "px");
    dropDown.css('left', leftDist + "px");

  }

  $('#searchGridSubmit').click(function() {
    // event.preventDefault(); // Stops browser from navigating away from page
    // const this = $(this);
    let searchQuery = $('#searchGridInput').val();
    console.log('func executed');
    window.location.href = "/cautare?q=" + searchQuery;

    // var country_id = this.value;
    // $("#state-dropdown").html('');

    // $.ajax({
    //         url: "../leads/leads-simple",
    //         type: "POST",
    //         data: {
    //         name: 'data',
    //         data: data,
    //     },
    //     dataType: 'json',
    //     success: function(result) {
    //         $('#state-dropdown').html('<option value="">Select State</option>');
    //         $.each(result.states, function(key, value) {
    //             $("#state-dropdown").append('<option value="' + value.id + '">' + value.name + '</option>');
    //         });
    //         $('#city-dropdown').html('<option value="">Select State First</option>');
    //     }
    // });
}); //submit form #2


$(document).ready(function() {

    $(".owl-carousel-they-trust").owlCarousel({
        items:3,
        loop:true,
        margin:10,
        autoplay:true,
        nav:false,
        autoplayTimeout:1000,
        responsive:{
            0:{
                items:3,
            },
            768:{
                items:4,
            },
            992:{
                items:5,
            },
            1200:{
                items:7,
            }
        }
    });

    $(".owl-carousel-team").owlCarousel({
        items:3,
        loop:true,
        margin:20,
        autoplay:true,
        nav:false,
        autoplayTimeout:3000,
        responsive:{
            0:{
                items:2,
            },
            576:{
                items:3,
            },
            1200:{
                items:5,
            }
        }
    });

    $(".owl-carousel-home-1").owlCarousel({
        items:1,
        loop:true,
        nav:false,
        URLhashListener:true,
        mouseDrag: false,
        touchDrag: false,
        pullDrag: false,
    });
    // $(".owl-carousel").owlCarousel();

    // const targetElement = document.querySelector('#my-element');
    const priceHighlightId = document.querySelectorAll('.rc_price_highlight');
    const priceHighlightIdList = [...priceHighlightId];
    priceHighlightIdList.forEach(divElement => {
        observer.observe(divElement);
    });

    const packagesTableId = document.querySelector('#rc_prices_table');
    console.log(packagesTableId);
    if(typeof packagesTableId !== "undefined" && packagesTableId){
        packagesTableObserver.observe(packagesTableId);
    }

    $(document).on('keypress',function(e) {
        if(e.which == 13) { //enter
        }
    });

    //     //on next click, hide dropdown if it's not within the dropdown
    //     $(document).on('click', function(e) {
    //         if(!$(e.target).is('#searchGridDDRes')){
    //             $('#searchGridDDRes').addClass('di_d_none');
    //             console.log('div hidden');
    //         } else{
    //             console.log('div not hidden');
    //         }
    //         console.log('not working');
    //     });

    // $('#searchGridInput').on("focusin", dipDDSearch);


    // $('#searchGridInput').on('click',function() {
    //     console.log('clicked');
    //     dipDDSearch();
    // });


    $('a.dipPropScrollH').on('click',function(e) {
        if (pathname.indexOf("proprietati") >= 0 || pathname.indexOf("ansambluri") >= 0){
            const sectionName = $(this).attr('href').substring(1);
            console.log(sectionName);
    
            if(sectionName == "overview") diScrollHorizH('dipPropNavTop', 'overview');
            if(sectionName == "features") diScrollHorizH('dipPropNavTop', 'features');
            if(sectionName == "price") diScrollHorizH('dipPropNavTop', 'price');
            if(sectionName == "schools") diScrollHorizH('dipPropNavTop', 'schools');
            if(sectionName == "neighbourhood") diScrollHorizH('dipPropNavTop', 'neighbourhood');
            if(sectionName == "supermarkets") diScrollHorizH('dipPropNavTop', 'supermarkets');
        }
    });

    function postContactForm(form, recaptchaToken) {
        const data = form.serialize() + '&recaptcha_token=' + recaptchaToken;
        $.post( "../leads/leads-simple", data)
            .done(function() {
                $('.joinUsFormSuccess').removeClass('di_d_none');
                $('.joinUsFormFailure').addClass('di_d_none');
                $('.joinUsForm').remove();
            })
            .fail(function(resp) {
                $('.joinUsFormFailure').removeClass('di_d_none');
            });
    }

    $(function() { //simple lead form
      $('.joinUsForm').submit(function(event) {
          event.preventDefault(); // Stops browser from navigating away from page
          const thisObj = $(this);
          grecaptcha.ready(function() {
              grecaptcha.execute(envRecaptchaSiteKey, {action: 'contact_form_submit'}).then(function(token) {
                  postContactForm(thisObj, token)
              });
          });
          return false;
      }); //submit form #1
    }); //function

    // cookie consent
    $(function() {
        const consent = localStorage.getItem('cookieConsent')
        if (consent === 'full' || consent === 'min') return
        $('.cookieConsent').css('bottom', '0px')
        $('.cookieAccept button').click(()=>{
            localStorage.setItem('cookieConsent', 'full')
            $('.cookieConsent').css('bottom', '-500px')
        })
        $('.cookieAccept a').click(()=>{
            localStorage.setItem('cookieConsent', 'min')
            $('.cookieConsent').css('bottom', '-500px')
        })
    }); //function


}); // ! doc ready
