var tailleEcranX = window.innerWidth;
var tailleEcranY = window.innerHeight;
//console.log('X '+tailleEcranX);
//console.log('Y '+tailleEcranY);

// Mobile
if (tailleEcranX <= 800) {

    jQuery(document).on('click', '#menu-item-67 > a', function(){
        jQuery('#menu-item-67 > .sub-menu').css('display', 'block');
    });

    jQuery(document).on('click', '#menu-item-84240 > a', function(){
        jQuery('#menu-item-84240 > .sub-menu').css('display', 'block');
    });
}

// tablette horizontale
if (tailleEcranX >= 768 && tailleEcranX <= 1388 && tailleEcranX > tailleEcranY) {
    jQuery(document).on('click', '#menu-item-67 > a', function(){
        jQuery('#menu-item-67 > .sub-menu').css('display', 'block');
    });

    jQuery(document).on('click', '#menu-item-84240 > a', function(){
        jQuery('#menu-item-84240 > .sub-menu').css('display', 'block');
    });

    if (jQuery('.priceMin').attr("placeholder") == 'Prix minimum') {
        jQuery('.priceMin').attr("placeholder", "Prix min");
    } else {
        jQuery('.priceMin').attr("placeholder", "Price min");
    }
    if (jQuery('.priceMax').attr("placeholder") == 'Prix maximum') {
        jQuery('.priceMax').attr("placeholder", "Prix max");
    } else {
        jQuery('.priceMax').attr("placeholder", "Price max");
    }





}







if(jQuery(".noirsemitransparent").length > 0){

    jQuery(".noirsemitransparent").each(function(){

        jQuery(this).find("a").append(jQuery(this).find("figcaption"));
        jQuery(this).find("a").append('<div class="layout"></div>');

        jQuery(this).find("a layout").height(jQuery(this).find("a img").height());
    });
}

function displayFilters(){
    jQuery(".FiltersPlace").show();
}
function closeFilters(){
    jQuery(".FiltersPlace").hide();
}

jQuery("div.customSelect,div.customSelectOption").on("click", function(e){
    if (e.target !== this)
      return;

    jQuery(this).toggleClass("opened");
});

jQuery("div.customSelect .selected,div.customSelectOption .selected").on("click", function(e){
    console.log(e.target)
    if (e.target !== this)
      return;

    jQuery(this).closest('.customSelect,.customSelectOption').toggleClass("opened");
});


jQuery("div.customSelect,div.customSelectOption").on("mouseleave", function(){

    jQuery(this).removeClass("opened")
});

jQuery("div.customSelect .option").on("click", function(e){
    if (e.target !== this)
      return;
    jQuery(this).find("input").trigger('click');
    jQuery(this).closest('.customSelect').find('.selected').html(jQuery(this).text());
    jQuery(this).closest('.customSelect').removeClass("opened");
    refreshMirrors();
})


if(jQuery("html").attr("lang") == 'en-US' && jQuery("body").hasClass("archive")){
    if(jQuery(".woocommerce-products-header__title.page-title").text() == 'Recherche'){
        jQuery(".woocommerce-products-header__title.page-title").html('Search');
        jQuery("title").html('Search - Sélection Villas Luxe');
        jQuery(".woocommerce-breadcrumb").html(jQuery(".woocommerce-breadcrumb").html().replace('Recherche', 'Search') );
    }
}


jQuery("div.customSelectOption .option").on("click", function(e){
    if (e.target !== this)
      return;
    jQuery(this).find("input").trigger('click');
})

jQuery("div.customSelectOption input").on("change", function(){
    formatCustomSelectOption(jQuery(this).closest("div.customSelectOption"));
    refreshMirrors();
});


jQuery("div.customSelect").each(function(){
    console.log(jQuery(this).html(), jQuery(this).find(".selected").text() , jQuery(this).find("input:checked").length);
    if(jQuery(this).find(".selected").text() == '' && jQuery(this).find("input:checked").length < 1){
        jQuery(this).find(".option").first().click();
    } else {
        jQuery(this).find("input:checked").closest('.option').trigger('click');
    }
});

function formatCustomSelectOption(elem){
    if(elem.find("input:checked").length == 0){
        elem.find(".selected").html(elem.data("default")).addClass("empty");
    } else {
        elem.find(".selected").html('').removeClass("empty");
        elem.find("input:checked").each(function(i, item){
            elem.children(".selected").append('<span class="lab">'+jQuery(this).closest("label").text()+'</span>');
        })
    }
}

function isUserLoggedIn(){
    return jQuery(".logged-in").length;
  }

function displayCriteria(){
    jQuery(".FiltersPlace").toggleClass('opened');
}

jQuery(".woof").first().remove();
jQuery("div.customSelectOption").each(function(){
    formatCustomSelectOption(jQuery(this));
})

jQuery(".FiltersPlace .inline100 input[type=checkbox]").on("change", function(){
    if(jQuery(this).is(":checked")){
        jQuery(this).closest("label").addClass("selected");
    } else {

        jQuery(this).closest("label").removeClass("selected");
    }
    refreshMirrors();
});


jQuery(".FiltersPlace .customSelectOption input[type=checkbox]").on("change", function(){
    if(jQuery(this).is(":checked")){
        jQuery(this).closest("label").addClass("selected0");
    } else {

        jQuery(this).closest("label").removeClass("selected0");
    }
});

var uuuu = false;

jQuery(".place.customInput").on("keyup", function(e){

    var event = window.event ? window.event : e;

    if(event.keyCode == 38){ // up
        var i = 0;
        jQuery(".autocomp div").each(function(w,item){
            if(jQuery(this).hasClass("selected")){
                jQuery(this).removeClass("selected");
                jQuery(".autocomp > div").eq( i -1 ).addClass("selected");
                return false;
            }
            i++;
        });

        if(jQuery(".autocomp div.selected").length == 0){
            jQuery(".autocomp div").first().addClass("selected");
        }
    } else if(event.keyCode == 40){ // down
        var i = 0;
        jQuery(".autocomp div").each(function(w,item){
            if(jQuery(this).hasClass("selected")){
                jQuery(this).removeClass("selected");
                jQuery(".autocomp > div").eq( i - (-1) ).addClass("selected");
                return false;
            }
            i++;
        });

        if(jQuery(".autocomp div.selected").length == 0){
            jQuery(".autocomp div").first().addClass("selected");
        }
    } else if(event.keyCode == 13){ // down
        var i = 0;
        if(jQuery(".autocomp div.selected").length > 0){

    jQuery(".place.customInput").val(jQuery(".autocomp div.selected").last().text());
    jQuery(".autocomp").hide();

        }
    } else {

    if(uuuu != false){
        uuuu.abort();
    }

    uuuu = jQuery.ajax({
        method: "POST",
        url: "/wp-json/sel/v1/autocomp/?t=" + jQuery(".place.customInput").last().val() + '&l=' + jQuery(".autocomp").data('lang'),
         processData: true,
         beforeSend: function ( xhr ) {
          if(isUserLoggedIn()){
           xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );

          }
         },
      })
        .done(function( msg ) {
            console.log(msg);
            jQuery(".autocomp").last().html('');
            jQuery.each(msg, function(i, item){
                console.log(i, item);
                jQuery(".autocomp").last().append('<b>'+ i +'</b>');

                jQuery.each(item, function(ic, itemc){
                    console.log(itemc);
                    jQuery(".autocomp").last().append('<div data-it="'+ itemc[0] +'" class="cc'+ itemc[0] +'" onclick="javascript:setCity('+itemc[0]+')">'+ itemc[1] +'</div>');
                });
            });
            jQuery(".autocomp").last().show();
            //jQuery(".loadresults").attr("onclick", "window.location.href='"+ msg +"';")
        });

    }
});

function setCity(i){
    jQuery(".place.customInput").val(jQuery(".cc"+i).last().text());
    jQuery(".autocomp").hide();
}

function refreshMirrors(){



        var params = {};

        params.priceMax = jQuery(".priceMax.mirrored").last().val();
        params.priceMin = jQuery(".priceMin.mirrored").last().val();
        params.surfaceMax = jQuery(".surfaceMax.mirrored").last().val();
        params.surfaceMin = jQuery(".surfaceMin.mirrored").last().val();
        params.place = jQuery(".place.customInput").last().val();
        params.piece = jQuery("input.piece:checked").serialize();
        params.chambre = jQuery("input.chambre:checked").serialize();
        params.chk = jQuery(".chk input:checked,.chk2 input:checked").serialize();
        params.cat = jQuery("input.category:checked").serialize();

        params.ag = agenceid;
        params.l = jQuery(".autocomp").data('lang');


        if(_.isEqual(params, ii)){} else {

            ii = params;

            if(uuu != false){
                uuu.abort();
                console.log(uuu);
            }

            uuu = jQuery.ajax({
                method: "POST",
                url: "/wp-json/sel/v1/search/get/",
                data: params,
                 processData: true,
                 beforeSend: function ( xhr ) {
                  if(isUserLoggedIn()){
                   xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );

                  }
                 },
              })
                .done(function( msg ) {
                    console.log(msg);
                    jQuery(".loadresults").attr("onclick", "window.location.href='"+ msg +"';")
                });

        }




}



function getLocation() {
    if (navigator.geolocation) {

    navigator.geolocation.getCurrentPosition(showPosition);
    } else {
     // Do nothing
    }
}

function displayPhone(i){
    jQuery(".phonePlace"+i+" > a").hide();
    jQuery(".phonePlace"+i+" > div").show();

    jQuery.ajax({
        method: "POST",
        url: "/wp-json/sel/v1/display_phone/",
        data: {
            'id':i
        },
         processData: true,
         beforeSend: function ( xhr ) {
          if(isUserLoggedIn()){
           xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );

          }
         },
      })
        .done(function( msg ) {});


}

function showPosition(position){
    jQuery.ajax({
        method: "POST",
        url: "/wp-json/sel/v1/search/getcit/",
        data: {
            'latitude':position.coords.latitude,
            'longitude':position.coords.longitude,
            'count':d,
            't':t
        },
         processData: true,
         beforeSend: function ( xhr ) {
          if(isUserLoggedIn()){
           xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );

          }
         },
      })
        .done(function( msg ) {

            if(msg != ""){
                jQuery(".wc-block-grid__products").html(msg);
            }
           // console.log(msg);
          //  jQuery(".loadresults").attr("onclick", "window.location.href='"+ msg +"';")
        });
}


function filter(){
    setTimeout(function(){

        var params = {};

        params.priceMax = jQuery(".priceMax.mirrored").last().val();
        params.priceMin = jQuery(".priceMin.mirrored").last().val();
        params.surfaceMax = jQuery(".surfaceMax.mirrored").last().val();
        params.surfaceMin = jQuery(".surfaceMin.mirrored").last().val();
        params.place = jQuery(".place.customInput").last().val();
        params.piece = jQuery("input.piece:checked").serialize();
        params.chambre = jQuery("input.chambre:checked").serialize();
        params.chk = jQuery(".chk input:checked,.chk2 input:checked").serialize();
        params.cat = jQuery("input.category:checked").serialize();
        params.ag = agenceid;

        if(_.isEqual(params, ii)){
            jQuery(".button.woof_submit_search_form").last().click();
        } else {

            ii = params;

            if(uuu != false){
                uuu.abort();
                console.log(uuu);
            }

            uuu = jQuery.ajax({
                method: "POST",
                url: "/wp-json/sel/v1/search/get/",
                data: params,
                 processData: true,
                 beforeSend: function ( xhr ) {
                  if(isUserLoggedIn()){
                   xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );

                  }
                 },
              })
                .done(function( msg ) {
                    console.log(msg);
                    window.location.href= msg ;
                });

        }
    }, 300);
}

function createAlert(){

    if(!jQuery("body").hasClass("logged-in")){

        modal(".alertCreatedLogFirst", "show");
    } else {


    setTimeout(function(){



        var params = {};


        params.priceMax = jQuery(".priceMax.mirrored").last().val();
        params.priceMin = jQuery(".priceMin.mirrored").last().val();
        params.surfaceMax = jQuery(".surfaceMax.mirrored").last().val();
        params.surfaceMin = jQuery(".surfaceMin.mirrored").last().val();
        params.place = jQuery(".place.customInput").last().val();
        params.piece = jQuery("input.piece:checked").serialize();
        params.chambre = jQuery("input.chambre:checked").serialize();
        params.chk = jQuery(".chk input:checked,.chk2 input:checked").serialize();
        params.cat = jQuery("input.category:checked").serialize();
        params.ag = agenceid;
        params.l = jQuery(".autocomp").data('lang');

    jQuery.ajax({
        method: "POST",
        url: "/wp-json/sel/v1/alert/create/",
        data: params,
         processData: true,
         beforeSend: function ( xhr ) {
          if(isUserLoggedIn()){
           xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );

          }
         },
      })
        .done(function( msg ) {
            modal(".alertCreated", "show");
        });







    }, 400);

    }
}

setInterval(function(){ refreshMirrors(); }, 200);


function modal(elem, action){
    if(action == 'hide'){
        jQuery(".modal"+elem+",.modalLayer"+elem+"").fadeOut(400);
    }
    if(action == 'show'){
        jQuery(".modal"+elem+",.modalLayer"+elem+"").fadeIn(400);
    }
}

setInterval(function(){
    if(jQuery(".rg-image img").is(":visible")){
      //  jQuery(".rg-image img").css('max-height', jQuery(window).height() - jQuery(".rg-thumbs").height() - 100);
      jQuery(".rg-image, .rg-image img").css('height', jQuery(window).height());

      jQuery(".rg-image img").css('object-fit', 'cover').css('width', '100%');
    }

}, 100);

function addToWishlist(id){
    if(isUserLoggedIn()){
    jQuery.ajax({
        method: "POST",
        url: "/wp-json/pmsa/v1/like/",
        data: {
          'product_id': id
        },
         processData: true,
         beforeSend: function ( xhr ) {
          if(isUserLoggedIn()){
           xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );

          }
         },
      })
      .done(function( msg ) {
          refreshLikeCount();

      });
    } else {
        modal(".alertCreatedLogFirst", "show");
    }
}

function removeFromWishlist(id){
    jQuery.ajax({
      method: "POST",
      url: "/wp-json/pmsa/v1/delike/",
      data: {
        'product_id': id
      },
       processData: true,
       beforeSend: function ( xhr ) {
        if(isUserLoggedIn()){
         xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );

        }
       },
    })
      .done(function( msg ) {
    refreshLikeCount();
      });
}


if(jQuery(".manageFav").length > 0){
    refreshLikeCount();
}


function refreshLikeCount(){
    jQuery.ajax({
      method: "GET",
      url: "/wp-json/pmsa/v1/like/",
      data: {
        'product_id': jQuery(".manageFav").data("id")
      },
       processData: true,
       beforeSend: function ( xhr ) {
        if(isUserLoggedIn()){
         xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );

        }
       },
    })
    .done(function( msg ) {

        if(msg.liked > 0){
        jQuery(".manageFav").addClass('liked').attr('href', 'javascript:removeFromWishlist('+ jQuery(".manageFav").data("id") +')');
        } else {
        jQuery(".manageFav").removeClass('liked').attr('href', 'javascript:addToWishlist('+ jQuery(".manageFav").data("id") +')');
        }


    });
}


function addToWishlistAgency(id){
    if(isUserLoggedIn()){

    jQuery.ajax({
        method: "POST",
        url: "/wp-json/pmsa/v1/like/agence/",
        data: {
          'agence_id': id
        },
         processData: true,
         beforeSend: function ( xhr ) {
          if(isUserLoggedIn()){
           xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );

          }
         },
      })
      .done(function( msg ) {
          refreshLikeCountAgency();

      });
    } else {
        modal(".alertCreatedLogFirst", "show");
    }
}

function removeFromWishlistAgency(id){
    jQuery.ajax({
      method: "POST",
      url: "/wp-json/pmsa/v1/delike/agence/",
      data: {
        'agence_id': id
      },
       processData: true,
       beforeSend: function ( xhr ) {
        if(isUserLoggedIn()){
         xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );

        }
       },
    })
      .done(function( msg ) {
    refreshLikeCountAgency();
      });
}


if(jQuery(".manageFavAgency").length > 0){
    refreshLikeCountAgency();
}


function refreshLikeCountAgency(){
    jQuery.ajax({
      method: "GET",
      url: "/wp-json/pmsa/v1/like/agence/",
      data: {
        'agence_id': jQuery(".manageFavAgency").data("id")
      },
       processData: true,
       beforeSend: function ( xhr ) {
        if(isUserLoggedIn()){
         xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );

        }
       },
    })
    .done(function( msg ) {

        if(msg.liked > 0){
        jQuery(".manageFavAgency").addClass('liked').attr('href', 'javascript:removeFromWishlistAgency('+ jQuery(".manageFavAgency").data("id") +')');
        } else {
        jQuery(".manageFavAgency").removeClass('liked').attr('href', 'javascript:addToWishlistAgency('+ jQuery(".manageFavAgency").data("id") +')');
        }


    });
}

jQuery(".mobile-menu ul").append(jQuery(".prehead div").html());
