$(document).ready(function () {
  (function ($) {
    $.fn.onPageLoad = function () {



      $('.pageTopTitle i').click(function(){
        $(this).parent().find('ul').toggleClass("active");
      })
      
      $('.pageMobileBrand').click(function (e) {
        $(this).toggleClass("active");
        $('.headerLeft').toggleClass("active");
        if($(this).hasClass("active")){
          $('.headerLeft').removeClass("animate__animated animate__fadeOutUp");
          $('.headerLeft').addClass("animate__animated animate__fadeInUp");
        }else{
          $('.headerLeft').removeClass("animate__animated animate__fadeInUp");
          $('.headerLeft').addClass("animate__animated animate__fadeOutUp");
        }
        setTimeout(function(){
          $('.headerLeft > ul > li > a').each(function(i){
            var $this=$(this);
              setTimeout(function(){
                $this.toggleClass("animate__animated animate__fadeInUp");
              },i*100);
          })
        },500)
        return false
      });



     
      

      $('.menuNavBtn').click(function (e) {
          if($(".pageInnerLeftCol.active").length>0){
              $('.pageInnerLeftCol').removeClass("active");
          }else{
            $('.pageInnerLeftCol').addClass("active")
          }
          return false;
      });

      $('.headerLeft ul li a').click(function (e) {
        if($(window).width()<768){
          if($(this).parent().find('ul').length>0){
            if($(this).parent().find("ul.active").length>0){
              $(this).parent().find("ul").removeClass("active");
            }else{
              $('.headerLeft ul li ul').removeClass("active");
              $(this).parent().find("ul").addClass("active");
            }
            return false;
          }
        }
      });

      $('.headerLeft ul li').hover(function (e) {
        if($(window).width()>=768){
          if($(this).find('ul').length>0){
            if($(this).find("ul.active").length>0){
              $(this).find("ul").removeClass("active");
            }else{
              $('.headerLeft ul li ul').removeClass("active");
              $(this).find("ul").addClass("active");
            }
            return false;
          }
        }
      });


      $('.headerLanguage a.active').click(function () {
				if ($(this).parent().find('ul:hidden').length > 0) {
					$(this).next('ul').stop(true, true).slideDown();
				} else {
					$(this).next('ul').stop(true, true).slideUp();
				}
				return false;
			})
      




      if($('.parallaxWrap').length>0){
        const urunDetayTarget=document.querySelector(".bigImgWrap");
        const urunDetayCallBack = (entries) => {
          if(entries[0]["isIntersecting"]==true && $(window).width()>768){
            $('.parallaxWrap').addClass("hidden");
          }else{
            $('.parallaxWrap').removeClass("hidden");
          }
        }

        const options={
          threshold:1
        }
        const urunDetayObServer = new IntersectionObserver(urunDetayCallBack,options);
        urunDetayObServer.observe(urunDetayTarget);
      }

      

      if ($(".sliderSlick").length > 0) {
        $(".sliderSlick").on("init", function (event, slick) {
          $(".sliderSlick").css("opacity", "1");
          var firstTitle=$(".sliderSlick .slick-slide.slick-current").data("title");
          $('.sliderText2').text(firstTitle);
        });
        $(".sliderSlick").not(".slick-initialized").slick({
          autoplay: true,
          fade: true,
          arrows:false,
          infinite: true,
          autoplaySpeed: 4000,
          speed: 1000,
          slidesToShow: 1,
          slidesToScroll: 1,
          dots: true,
          focusOnSelect: true
        });
        $('.sliderSlick').on('beforeChange', function(event, slick, currentSlide, nextSlide){
            $('.sliderSlick .slick-slide h2').removeClass('animate__fadeInLeft').addClass("animate__animated animate__fadeOutRight");
            $('.sliderSlick .slick-slide p').removeClass('animate__fadeInLeft').addClass("animate__animated animate__fadeOutRight");
            $('.sliderSlick .slick-slide .detayBtn').removeClass('animate__fadeInLeft').addClass("animate__animated animate__fadeOutRight");
            setTimeout(() => {    
              $('.sliderSlick .slick-slide h2').removeClass("animate__fadeOutRight").addClass('animate__fadeInLeft');
              $('.sliderSlick .slick-slide p').removeClass("animate__fadeOutRight").addClass('animate__fadeInLeft');
              $('.sliderSlick .slick-slide .detayBtn').removeClass("animate__fadeOutRight").addClass('animate__fadeInLeft');
            }, 1500);
        });
        
        

       /* $('.sliderSlick').on('beforeChange', function(event, slick, currentSlide, nextSlide){
          var firstTitle=$(".sliderSlick .slick-slide[data-slick-index="+nextSlide+"]").data("title");
          $('.sliderText2').text(firstTitle);
        });

        if($(window).width()<768){
          $('.sliderSlick').slick('slickUnfilter');
          $(".sliderSlick").slick("slickFilter",".mobil")
        }else{
          $('.sliderSlick').slick('slickUnfilter');
          $(".sliderSlick").slick("slickFilter",".desktop")
        }
        $(window).resize(function () { 
          $('.sliderSlick').slick('slickUnfilter');
          if($(this).width()<768){
            $(".sliderSlick").slick("slickFilter",".mobil")
          }else{
            $(".sliderSlick").slick("slickFilter",".desktop")
          }
        });*/


      }
      

   
      


      if ($(".blogSlick").length > 0) {
        $(".blogSlick").on("init", function (event, slick) {
          $(".blogSlick").css("opacity", "1");
        });
        $(".blogSlick")
          .not(".slick-initialized")
          .slick({
            autoplay: true,
            infinite: true,
            autoplaySpeed: 4000,
            slidesToShow: 4,
            slidesToScroll: 4,
            dots: false,
            focusOnSelect: true,
            responsive: [
              {
                breakpoint: 480,
                settings: {
                  slidesToShow: 1,
                  slidesToScroll: 1,
                },
              },
            ],
          });
      }

      if($('.slider-pro').length>0){
        $('.slider-pro').sliderPro({
          fade: false,
          arrows: true,
          buttons: false,
          fullScreen: false,
          responsive: true,
          aspectRatio:-1,
          autoHeight:true,
          autoSlideSize:true,
          width: 600,
          height: 500,
          autoplay: false,
          thumbnailArrows: true,
          thumbnailsPosition: 'right',
          loop: false,
          thumbailWidth: 300,
          breakpoints: {
            768: {
              thumbnailsPosition: 'bottom'
            }
          }
        });
      }

      if($('img.lazy').length>0){
        $("img.lazy").lazyload();
      }



      
      if($('.selectize').length>0){
        $('.selectize').selectize();
        $(".selectize-input input").prop('readonly','readonly');
      }

      if ($(".fancyboxVideo").length > 0) {
        $(".fancyboxVideo").click(function(e) {
          e.preventDefault();
          var videoUrl = $(this).attr("href");
          var embedUrl = videoUrl.replace("watch?v=", "embed/");
          $.fancybox({
            type: "iframe",
            href: embedUrl,
            width: 800, // İsteğe bağlı olarak boyutları ayarlayabilirsiniz
            height: 450,
            autoSize: false,
            aspectRatio: true,
          });
        });
      }

      $(document).on("change", ".iller", function () {
        var deger = parseInt($(this).val());
        $.ajax({
          type: "POST",
          data: "deger=" + deger,
          url: base_url + "process/ilce",
          success: function (deger) {
            sonuc = $.trim(deger);
            var json_obj = $.parseJSON(sonuc); //parse JSON
            if (json_obj.result == "success") {
              $(".ilceler").empty();
              $(".ilceler").append(json_obj.ilceler);
            } else {
              swal("Hata!", "İlçe bulunamadı...", "warning");
            }
          },
        });
      });


      if($('.loader').length>0){
        $('.loader').addClass("gizle");
      }

      if ($(".fancybox").length > 0) {
        $(".fancybox").fancybox();
      }
      if ($(".phone_number").length > 0) {
        $(".phone_number").mask("0999 999 99 99");
      }
      if ($(".kartTarihMask").length > 0) {
        $(".kartTarihMask").mask("99/99");
      }
      if ($(".kartCvcMask").length > 0) {
        $(".kartCvcMask").mask("999");
      }
      if ($(".kartNoMask").length > 0) {
        $(".kartNoMask").mask("9999-9999-9999-9999");
      }
      if ($(".price_range").length > 0) {
        $(".price_range").number(true, 2, ",", ".");
      }
      if ($(".tcNumber").length > 0) {
        $(".tcNumber").mask("99999999999");
      }

     

      function submitButtonTextChange($this,defaultText){
        $this.find("button.btn").prop("disabled", false);
        $this.find("button.btn span").text(defaultText);
      }


      function ajaxSend($this,formData,defaultText){
        $.ajax({
          type: "post",
          url: $this.attr("action"),
          data: formData,
          contentType: false,
          cache: false,
          processData: false,
          success: function (sonuc) {
            sonuc = $.trim(sonuc);
            var json_obj = $.parseJSON(sonuc); //parse JSON


            if(json_obj.islem=="sepet"){
              $('.topNotification').addClass("active");
              $('.topNotification ul li:last').html(json_obj.mesaj);
              setTimeout(function(){
                $('.topNotification').removeClass("active");
              },3000);
              submitButtonTextChange($this,defaultText);
              $('.headerRight ul li.sepet a b').text(json_obj.toplam);
              return false;
            }

            if(json_obj.result=="process"){
                $this.append('<input type="hidden" name="process" value="1">');
                $this.addClass("formNoAjax");
                $this.removeClass("gonder");
                $('form.formNoAjax').submit();
            }


            swal(
              {
                html:true,
                title: json_obj.baslik,
                text: json_obj.mesaj,
                type: json_obj.result,
                showCancelButton: false,
                confirmButtonColor: "#1976D2",
                confirmButtonText: tamam,
                closeOnConfirm: false,
                closeOnCancel: false,
                allowEscapeKey: false,
                allowOutsideClick: false,
              },
              function (isConfirm) {
                if (isConfirm) {
                  swal.close();

                  if (json_obj.location == "reload") {
                    location.reload();
                  }
                  if (
                    json_obj.location != "" &&
                    json_obj.location != "reload"
                  ) {
                    window.location = json_obj.location;
                  }
                }
              }
            );


            submitButtonTextChange($this,defaultText);

            $(".loader-capsul").stop(true, true).fadeOut();
          },
        });
      }

      $(document).on("submit", ".gonder", function (e) {
        $(".loader-capsul").stop(true, true).fadeIn();
        var $this = $(this);
        $this.find("button.btn").prop("disabled", true);
        var defaultText = $this.find("button.btn span").text();
        $this.find("button.btn span").text(bekleyiniz);
        
        var formData=new FormData(this);
        

        
        if ($("input[name='recaptcha_Cevap']").length > 0) {
          var token;
          grecaptcha.ready(function() {
            grecaptcha.execute('6LcWGIAcAAAAACzaqchrDOHCyM8yOFp7VguIM2GS', {
              action: 'submit'
            }).then(function(result) {
              token = result;
              var recaptchaCevabi = document.getElementById('recaptchaCevabi');
              recaptchaCevabi.value = result;
            });
          });
          setTimeout(function() {
            formData.append('recaptcha_Cevap', token);
            ajaxSend($this,formData,defaultText);
          }, 2000);
        } else {
          ajaxSend($this,formData,defaultText);
        }

        
        
        
        return false;
      });

      $.cookiePolicy = function (options) {
        options = $.extend(
          {
            append: "",
            text: "mesaj",
          },
          options
        );
        if (options.append == "") {
          alert("append boş olamaz");
        }
        var htmlView =
          '<div class="cookie-popup"><div class="content"><div class="item">' +
          options.text +
          '</div><div class="item"><button class="btn btn-close"><i class="icofont-close-line"></i></button></div></div></div>';

        var cookie = readCookie("cP");
        if (!cookie) {
          $(options.append).append(htmlView);
        }

        $(".cookie-popup .content button.btn").click(function () {
          var currentDate = new Date();
          expirationDate = new Date(
            currentDate.getFullYear(),
            currentDate.getMonth(),
            currentDate.getDate() + 1,
            0,
            0,
            0
          );
          setCookie("cP", "1", expirationDate);
          $(this).parents(".cookie-popup").fadeOut();
        });

        function setCookie(c_name, value, exdays) {
          //cookie oluşturma
          var c_value =
            escape(value) +
            (exdays == null ? "" : "; path=/; secure; expires=" + exdays);
          document.cookie = c_name + "=" + c_value;
        }

        function readCookie(key) {
          currentcookie = document.cookie;
          if (currentcookie.length > 0) {
            firstidx = currentcookie.indexOf(key + "=");
            if (firstidx != -1) {
              firstidx = firstidx + key.length + 1;
              lastidx = currentcookie.indexOf(";", firstidx);
              if (lastidx == -1) {
                lastidx = currentcookie.length;
              }
              return unescape(currentcookie.substring(firstidx, lastidx));
            }
          }
          return "";
        }
      };

      $.htmlPopup = function (options) {
        options = $.extend(
          {
            content: "",
            themeClass:""
          },
          options
        );
        if (options.content == "") {
          alert("content boş olamaz");
        }
        var htmlView = options.content;

        var themeClass = "";
        if (options.themeClass != "") {
          themeClass = options.themeClass;
        }
        $("body").append(
          '<div class="htmlPopupContainer ' +
            themeClass +
            '">' +
            htmlView +
            "</div>"
        );

        $(".htmlPopupContainer span.close").click(function () {
          $(".htmlPopupContainer").remove();
        });
      };

      function swalMessage(data) {
        swal(
          {
            html: true,
            title: data.baslik,
            text: data.mesaj,
            type: data.result,
            showCancelButton: false,
            confirmButtonColor: "#1976D2",
            confirmButtonText: tamam,
            closeOnConfirm: false,
            closeOnCancel: false,
            allowEscapeKey: false,
            allowOutsideClick: false,
          },
          function (isConfirm) {
            if (isConfirm) {
              swal.close();
              if (data.location == "reload") {
                location.reload();
              }
              if (data.location != "" && data.location != "reload") {
                window.location = data.location;
              }
            }
          }
        );
        if ($('input[name="satis_kosullari[]"]').length > 0) {
          $('input[name="satis_kosullari[]"]').prop("checked", true);
        }
        $(".loader-capsul").stop(true, true).fadeOut();
      }
    };
  })(jQuery);

  $("body").onPageLoad();
});
