﻿sayfayiIlkZiyaret = new Date();
var isChrome = /chrome/.test(navigator.userAgent.toLowerCase()) && /google inc/.test(navigator.vendor.toLowerCase());
var globalBlokModel = 0;
var ProductPager = {};
var urunModulCount = 0;
var isProductsLoaded = false;
var isBlocksLoaded = false;
var magazaBolgeSecimi = getCookie("magazaBolgeSecimi") && siteSettings.magazaModulu != null && siteSettings.magazaModulu.magazaStokSatis.aktif ? JSON.parse(decodeURIComponent(getCookie("magazaBolgeSecimi")).replace(/\+/g, " ")) : null;
var memberCart = [];
var magazaBolgeAdresleri = null;
var categoryListProduct = [];
var originalSiteTitle = document.title;
window.dataLayer = window.dataLayer || []; //gtag kullanmayan sitelerde de datalayer methodlar hata veriyordu o nedenle genele bir window.dataLayer tanımlası yapıldı.

$.getScript("https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js");
$.getScript("https://www.gstatic.com/firebasejs/8.10.1/firebase-messaging.js");

//uygulamada sifremi unuttum sayfasında header ve footer gizleme
if (document.getElementsByClassName('SifremiUnuttumContent').length > 0 || document.getElementsByClassName('UyelikOnayContent').length > 0) {
    var UserIos = navigator.userAgent.split("TicimaxiOS").length;
    var UserAndroid = navigator.userAgent.split("TicimaxAndroid").length;
    if (UserIos > 1 || UserAndroid > 1) {
        if (document.getElementById('header')) {
            document.getElementById('header').style.display = "none";
        }
        if (document.getElementById('footer')) {
            document.getElementById('footer').style.display = "none";
        }
        if (document.getElementById('headerNew')) {
            document.getElementById('headerNew').style.display = "none";
        }
        if (document.getElementsByClassName('footerTemp').length > 0) {
            document.getElementsByClassName('footerTemp')[0].style.display = "none";
        }
    }
}

function productScrollPosition() {
    if (localStorage.getItem('lastVisitInfo')) {
        var lastVisitInfo = JSON.parse(localStorage.getItem('lastVisitInfo'));
        var productUrl = lastVisitInfo.lastVisitProduct[lastVisitInfo.lastVisitProduct.length - 1];
        $('.ItemOrj').each(function () {
            var thisUrl = $(this).find('.productName > a').attr('href');
            if (thisUrl === productUrl) {
                $(document).scrollTop($(this).offset().top - 200);
            }
        });
    }
}

function smoothScrollTo(elem, offset) {
    if (!offset) { offset = 0 }
    var pos = 0;
    pos = $(elem).offset().top;
    $('html, body').animate({
        scrollTop: pos - offset
    }, 550);
}

String.prototype.toDateFromAspNet = function () {
    var dte = eval("new " + this.replace(/\//g, '') + ";");
    return dte;
};

var urunDosyaYuklemeZorunlu = true;
var uyeSepet;
function refreshSepet(urunObj) {
    var sepetTemplate = $("#scriptTemplateGlobalSepetUrun").html();
    if (sepetTemplate !== undefined) {

        var success = function (res) {

            memberCart = res.cart;
            //$('.SProduct').html(Handlebars.compile(sepetTemplate)(res.cart));
            //$('#spnUstSepetToplamTutar').html(res.cart.tAmount);
            //$('#spnTopSepetToplamTutar').html(res.cart.tAmount);
            //$('#spnTopSepetToplamUrun').html(res.cart.pCount);
            //$('#snpMobilSepetUrunSayisi').html(res.cart.pCount);

            //if (res.cart.products.length <= 0) {
            //    $('#ulUstSepetteUrunYok').show();
            //}
            //else {
            //    $('#ulUstSepetteUrunYok').hide();
            //}
            //BlockTemplate
            if ($('#divSepetblock').length > 0) {
                if (res.cart.products.length <= 0) {
                    $('#divSolBlokSepetUrunyok').show();
                    $('#SepetBlockGenelTotal').hide();
                    $('#divSepetSolBlok').hide();
                    $('#divSepetSolBlok').html("");
                    $('#divBlokSepetGenelToplam').html("");
                }
                else {
                    $('#divSepetSolBlok').html(Handlebars.compile($("#scriptTemplateSepetUrun").html())(res.cart));
                    $('#divBlokSepetGenelToplam').html(Handlebars.compile($("#scriptTemplateGenelToplam").html())(res.cart));
                    $('#divSepetSolBlok').show();
                    $('#divSolBlokSepetUrunyok').hide();
                    $('#SepetBlockGenelTotal').show();
                    if (siteSettings.magazaModulu != null && siteSettings.magazaModulu.magazaStokSatis.aktif && siteSettings.magazaModulu.magazaStokSatis.magazaTemsilciAyar.aktif && localStorage.sepetHazirlayan && siteSettings.magazaModulu.magazaStokSatis.magazaTemsilciAyar.sepetBloktaGoster) {
                        var hazirlayanKisi = JSON.parse(localStorage.sepetHazirlayan);
                        var puanOrtalama = hazirlayanKisi.puan > 0 ? (hazirlayanKisi.puan / hazirlayanKisi.puanVerenSayisi) : 0;
                        var hazirlayanHtml = "<div class='hazirlayanMesaj'>" + siteSettings.magazaModulu.magazaStokSatis.magazaTemsilciAyar.sepetMesaj.replace("{ISIM}", hazirlayanKisi.isim).replace("{SOYISIM}", hazirlayanKisi.soyisim) + "</div>";
                        hazirlayanHtml += "<div class='hazirlayanKisi'><div class='hazirlayanIsim'>" + hazirlayanKisi.isim + " " + hazirlayanKisi.soyisim + "</div>";
                        hazirlayanHtml += "<div class='hazirlayanMagaza'>" + hazirlayanKisi.magaza + "</div>";
                        hazirlayanHtml += "<div class='hazirlayanPuan'>" + hazirlayanKisi.puan + "</div>";
                        hazirlayanHtml += "<div class='hazirlayanResim'><img src='" + hazirlayanKisi.resim + "'/></div></div>";
                        $("#sepetBlokHazirlayanBilgisi").html(hazirlayanHtml);
                        $("#sepetBlokHazirlayanBilgisi .hazirlayanPuan").rateYo({
                            rating: puanOrtalama,
                            readOnly: true,
                            starWidth: "20px"
                        });
                        $("#sepetBlokHazirlayanBilgisi").show();
                    }
                }
            }

            if (typeof sepetBindRefresh != "undefined") {
                sepetBindRefresh(res);
            }

            if (typeof cartCallBack != "undefined") {
                cartCallBack(res);
            }

            if (typeof urunObj != "undefined") {
                var product = res.cart.products.filter(function (x) { return x.vId === urunObj.UrunId; })[0];
                remarketingAddToCart(product);
            }

            InitInCart();

            if (siteSettings.personaClickAktif) {
                if (typeof personaclick !== 'undefined') {
                    personaclick('track', 'cart', res.cart.products.map(function (x) { return { id: x.pId, amount: x.piece }; }));
                }
            }

            if (typeof productDetailModel != "undefined" && productDetailModel.productVariantData == null) {
                kampanyaHesapla(productDetailModel.productId, productDetailModel.mainVariantId, productDetailModel.productPriceKDVIncluded);
            }
        };

        var memberCartStorage = getCartLocalStorage();
        if (memberCartStorage !== null && new Date(memberCartStorage.expiry).addHours(1) > new Date() && memberCartStorage.language === globalModel.languageCode && memberCartStorage.currency === globalModel.currency) {
            success(memberCartStorage.cart);
        }
        else {
            ticimaxApi.cart.getLite(null, function (res) {
                addCartLocalStorage(res);
                success(res);
            });
        }
    }
}

function SaveYorum(isUpdate) {
    var formAyar = siteSettings.urunAyar.urunDetayAyar.yorumFormAyar;
    var recommended = formAyar.tavsiye.goster && formAyar.tavsiye.zorunlu ? $("input[name=rdTavsiye]:checked").val() : "";
    var age = formAyar.yas.goster && formAyar.yas.zorunlu ? $("input[name=rdYas]:checked").val() : "";
    var rating = formAyar.puanlama.goster && formAyar.puanlama.zorunlu ? $(".detayYorumFormRating .commentStars").attr("data-rating") : "0";
    if (TiciValidation('.frmUrunDetayYorumYaz') && typeof recommended != "undefined" && typeof rating != "undefined") {
        var productId = "";
        if (!window.commentProductId) {
            if (typeof parent.productDetailModel != 'undefined') {
                productId = parent.productDetailModel.productId;
            }
            else {
                productId = productDetailModel.productId;
            }
        } else {
            productId = window.commentProductId;
        }

        var Images = [];
        if (typeof commentimageFile0 != 'undefined') {
            if (commentimageFile0 && commentimageFile0 != null) {
                Images.push(commentimageFile0)
            }
        }
        if (typeof commentimageFile1 != 'undefined') {
            if (commentimageFile1 && commentimageFile1 != null) {
                Images.push(commentimageFile1)
            }
        }
        if (typeof commentimageFile2 != 'undefined') {
            if (commentimageFile2 && commentimageFile2 != null) {
                Images.push(commentimageFile2)
            }
        }

        var commentReq =
        {
            Title: $('#txtbxYorumBaslik').val(),
            Name: $('#txtbxYorumIsim').val(),
            Rating: parseInt(rating),
            Recommended: parseInt(recommended) == 1,
            Message: $('#txtbxYorumMesaj').val(),
            Age: age,
            ProductId: productId,
            ShowName: $("#chkIsimGoster").is(":checked"),
            Images: Images
        };

        if (typeof isUpdate != "undefined" && isUpdate) {
            commentReq.CommentId = parseInt($("#yorumYazYorumId").val()) || 0;
            commentReq.IsUpdate = true;
        }

        $('.YorumContIcerik .yorumBtn #btnYorumKaydet').addClass('disabledClick');
        ticimaxApi.product.saveProductComment(commentReq, function (response) {
            var ticiNoty = parent.TiciNoty;
            if (typeof ticiNoty == 'undefined') {
                ticiNoty = TiciNoty;
            }

            if (!response.isError) {
                if (typeof TabGetComments != "undefined") {
                    TabGetComments();
                }
                ticiNoty.Show({ message: translateIt('UrunDetay_YorumKaydedildi'), type: 'success' });
                $('#yorumYaz .modal-close').click();
                $('.YorumContIcerik .yorumBtn #btnYorumKaydet').removeClass('disabledClick');
            } else {
                ticiNoty.Show({ message: response.errorMessage, type: 'error' });
                $('.YorumContIcerik .yorumBtn #btnYorumKaydet').removeClass('disabledClick');
            }
        });
    } else {
        if (typeof recommended == "undefined" && $(".detayYorumFormOneri .tici-valid-error").length == 0) {
            $(".detayYorumFormOneri").append('<span class="tici-valid-error alert alert-danger">Bu Alan Zorunludur</span>');
        }
        if (typeof rating == "undefined" && $(".detayYorumFormRating .tici-valid-error").length == 0) {
            $(".detayYorumFormRating").append('<span class="tici-valid-error alert alert-danger">Bu Alan Zorunludur</span>');
        }
        if (typeof age == "undefined" && $(".detayYorumYas .tici-valid-error").length == 0) {
            $(".detayYorumYas").append('<span class="tici-valid-error alert alert-danger">Bu Alan Zorunludur</span>');
        }
    }
}


function getProductDetailAsync(prod, goster) {
    var getProductDetailAsync = new Promise((resolve, reject) => {
        ticimaxApi.product.getProductDetail({ ProductId: prod.productId }, function (response) {
            resolve(response);
        });
    });
    getProductDetailAsync.then((response) => {
        productDetailModel = response.detailModel;
        YorumYazGoster(prod, goster, true);
    });
}
function YorumYazGoster(prod, goster, detailFull) {
    if (typeof goster == "undefined") {
        goster = false;
    }
    if (typeof prod == 'undefined') {
        prod = {
            productId: productDetailModel.productId
        }
    }
    if (siteSettings.siparisSayisiKadarYorumYapAktif && !detailFull) {
        getProductDetailAsync(prod, goster);
        return;
    }
    if (siteSettings.siparisSayisiKadarYorumYapAktif && productDetailModel.memberCommentIds.length > 0) {
        ticimaxApi.product.getComments({ commentIds: productDetailModel.memberCommentIds }, function (response) {
            //imgCommentsList = response.onlyPhotoComments;
            //if (imgCommentsList != null && imgCommentsList.length > 0) {
            //    lazyLoad();
            //    $('.divYorumlarV2SectionImgList .v2ImgList').owlCarousel({
            //        nav: false,
            //        dots: false,
            //        margin: 10,
            //        autoWidth: true,
            //    });
            //}

            if (response.numberOfApprovedComments > 0) {
                var onaysizYorumSayisi = response.totalCommentCount - response.numberOfApprovedComments;
                var yorumHakki = productDetailModel.memberTotalNumberOfProductOrders - response.totalCommentCount;
                if (onaysizYorumSayisi > 0) {
                    if (yorumHakki == 0) {
                        var onaysizYorumlar = response.comments.filter(function (x) { return !x.approved });
                        if (onaysizYorumlar.length > 0) {
                            var onaysizYorum = onaysizYorumlar[0];
                            TiciNoty.Show({ type: 'danger', message: translateIt('Onay_Bekleyen_Yorum_Mevcut') });
                            //Son onaysız yorumu göster. onaysizyorum değişkenindeki veriler popupa set edilmeli
                        }
                    }
                    else if (yorumHakki < 0) {
                        TiciNoty.Show({ type: 'info', message: translateIt('Yorum_Siparis_Sayisi_Hak') });
                        //Geliştirme öncesi yorumlar için bu kısma düşebilir bu durumda uyarı verilebilir.
                    }
                }
                else {
                    if (yorumHakki > 0) {
                        GetYorumYazSablon();
                    }
                    else {
                        TiciNoty.Show({ type: 'info', message: translateIt('Yorum_Siparis_Sayisi_Hak') });
                        //Bu durumda uyarı verilebilir.
                    }
                }
            }
            else {
                var onaysizYorumlar = response.comments.filter(function (x) { return !x.approved });
                if (onaysizYorumlar.length > 0) {
                    var onaysizYorum = onaysizYorumlar[0];
                    TiciNoty.Show({ type: 'danger', message: translateIt('Onay_Bekleyen_Yorum_Mevcut') });
                    //Son onaysız yorumu göster. onaysizyorum değişkenindeki veriler popupa set edilmeli.
                }
            }
        });
    }
    else {
        GetYorumYazSablon(0, prod, goster);
    }
}

function GetYorumYazSablon(commentId, prod, goster) {
    if (typeof goster != "undefined" && goster) {
        $('html,body').animate({ scrollTop: $('a[href="javascript:YorumYazGoster();"]').offset().top - 150 }, 'medium');
    }
    else {
        commentId = typeof commentId != "undefined" ? commentId : 0;
        var sablonYolu = siteSettings.siteYonetimAyar.sablonAyar.sablonYolu;
        $.get(sablonYolu + "UrunDetay/YorumYaz.html", function (data) {
            var compiled = Handlebars.compile(data);
            var productDescription = $(".urunTabAlt").html();
            if (prod) {
                productDetailModel = prod;
            }

            var yorumYazReq = {
                IsAuthenticated: globalModel.isAuthenticated,
                ProductDetailModel: typeof productDetailModel !== 'undefined' ? productDetailModel : "",
                ProductDescription: typeof productDescription !== 'undefined' ? productDescription : ""
            };

            createModal({
                id: "yorumYaz", content: compiled(yorumYazReq)
            });

            if (globalModel.isAuthenticated) {
                setTimeout(function () {
                    $('#txtbxYorumIsim').val(globalModel.member.memberName);
                    $("#yorumYazYorumId").val(commentId);
                }, 500);

                $('body').on('click', '.detayYorumFormRating .commentStars li', function () {
                    var classStr = $(this).attr("class");
                    var star = parseInt(classStr.split("svgStar")[1]);
                    $(this).parent().attr("data-rating", star);
                });

                if (typeof productDetailModel !== 'undefined' && productDetailModel.m169804) {
                    if (typeof cities === 'undefined' || cities.length == 0) {
                        ticimaxApi.member.getCity({ countryId: 1 }, function (res) {
                            cities = res.cities;
                            FillCitiesInYorum();
                        });
                    }
                    else {
                        FillCitiesInYorum();
                    }
                }
            }
        });
    }
}
function FillCitiesInYorum() {
    if (typeof cities !== 'undefined' && cities.length > 0) {
        for (var i = 0; i < cities.length; i++) {
            var o = new Option(cities[i].cityName, cities[i].cityId);
            $(o).html(cities[i].cityName);
            $("#selectCity").append(o);
        }
    }
}

$(document).on('click', ".detayYorumFormRating .rating i", function () {
    var classStr = $(this).attr("class");
    var star = classStr.split("-")[1];
    $(this).parent().attr("data-rating", star);
});

function validateProductFile(commentImage, $this) {
    var forCommentImage = typeof commentImage != "undefined" && commentImage == true;
    var productFiles = forCommentImage ? document.getElementById($this.id).files : document.getElementById('fuUrunSiparisDosya').files;

    //Size Kontrol
    for (var i = 0; i < productFiles.length; i++) {
        var sizeControl = productFiles[i].size / 1024 / 1024;
        if (sizeControl > 5) {
            TiciNoty.Show({ message: 'Yüklediğiniz dosya(lar) içerisinde 5MB aşan dosyalar bulunmaktadır.', type: 'danger' });
            return;
        }
    }

    if (!forCommentImage) {
        if (productFiles.length <= 0 && productDetailModel.productFileUploadIsRequire) {
            TiciNoty.Show({ message: 'Lütfen ürüne dosya yükleyiniz.', type: 'danger' });
            return;
        }

        if (productFiles.length > productDetailModel.productFileUploadMaxSize) {
            TiciNoty.Show({ message: ('Maximum ' + productDetailModel.productFileUploadMaxSize + ' dosya yükleyebilirsiniz.'), type: 'danger' });
            return;
        }
    }

    if (productFiles.length > 0) {
        var validFilesTypes = ["gif", "png", "jpeg", "jpg", "doc", "docx", "xls", "pdf", "zip", "rar"];

        if (forCommentImage) {
            validFilesTypes = ["gif", "png", "jpeg", "jpg"];
        }

        for (var i = 0; i < productFiles.length; i++) {
            var ext = productFiles[i].name.substring(productFiles[i].name.lastIndexOf(".") + 1, productFiles[i].name.length).toLowerCase();

            var result = validFilesTypes.filter(function (el) { return el === ext });
            if (result.length <= 0) {
                if (forCommentImage) {
                    var filesMessage = ('Dosya tipi desteklenmemektedir. Dosya yorumunuza eklenmeyecektir, lütfen yüklediniz dosya(ları) kontrol ediniz. Desteklenen dosya tipleri ' + validFilesTypes.toString());
                } else {
                    var filesMessage = ('Dosya tipi desteklenmemektedir. Dosya siparişinize eklenmeyecektir, lütfen yüklediniz dosya(ları) kontrol ediniz. Desteklenen dosya tipleri ' + validFilesTypes.toString());
                }
                TiciNoty.Show({ message: filesMessage, type: 'danger' });
                return false;
            }
        }
        return true;
    }
    return true;
}

function remarketingAddToCart(product) {
    if (typeof ga == "function") {
        ga('ec:addProduct', {
            'id': product.pId,
            'name': product.name,
            'price': product.priceValue,
            'quantity': product.piece
        });
        ga('ec:setAction', 'add');
        ga('send', 'event', 'UX', 'click', 'sepete ekleme');
    }
}

var AddToCartParams = {};

function generateNotify(text, type, timeout) {
    TiciNoty.Show({ message: text, type: type });
}

function closeNotify(notifyObj) {
    setTimeout(function () {
        $.noty.close(notifyObj.options.id);
    }, 2000);
}


function GetControlValue(controlId) {
    var currValue = $(controlId).val();
    return currValue;
}
function closeCerezUyarisi() {
    localStorage.setItem("CerezUyariGosterildi", true);
    $('#cerekKullanimUyari').hide();
}

$(document).ready(function () {
    if (typeof window.cart !== 'undefined') {
        window.cart.get.execute();
    }
    else {
        top.window.cart.get.execute();
    }

    var csrf_token = $('input[name="__RequestVerificationToken"]').val();
    $.ajaxSetup({
        beforeSend: function (xhr, settings) {
            if (!this.crossDomain) {
                xhr.setRequestHeader("X-AjaxPro-Token", csrf_token);
            }
        }
    });

    if (siteSettings.cerezUyarisiGoster && localStorage.getItem("CerezUyariGosterildi") == null) {
        //localStorage.setItem("CerezUyariGosterildi", true);
        $('#cerekKullanimUyari').show();

    } else {
        $('#cerekKullanimUyari').hide();
    }

    //$('#spnTopSepetToplamTutar').html("");
    //$('#spnTopSepetToplamUrun').html("");

    //ResetSliders();

    SosyalGirisKontrol();

    $(".fancyboxIframe").fancybox({
        'width': '100%',
        'height': '100%',
        'autoScale': false,
        'transitionIn': 'none',
        'transitionOut': 'none',
        'type': 'iframe'
    });

    $(".kargomNeredeIframe").fancybox({
        'width': '400px',
        'type': 'iframe',
        'transitionIn': 'none',
        'transitionOut': 'none',
    });

    $(".newUserLoginContent .fancyboxIframe").fancybox({
        'width': '800px',
        'height': '100%',
        'autoScale': false,
        'transitionIn': 'none',
        'transitionOut': 'none',
        'type': 'iframe'
    });

    $(".uyeOlColItem .fancyboxIframe, .userSozlesmeDiv .fancyboxIframe").fancybox({
        'width': '700px',
        'autoScale': false,
        'transitionIn': 'none',
        'transitionOut': 'none',
        'type': 'iframe'
    });

    if (siteSettings.kampanyaTeklifAktif) {

        setTimeout(kampanyaTeklifleri, teklifKontrolTimer);

        $('body').on('mouseleave', function (event) {
            if (!$('body').hasClass('kamp_cikis')) {
                $('body').addClass('kamp_cikis');
                kampanyaTeklifleri(1);
            }
        });
    }
    if (siteSettings.globalPopupAktif) {
        setTimeout(AdminPopupControl, popupKontrolTimer);
    }
    if (siteSettings.pasifSekmeMesaji !== null && siteSettings.pasifSekmeMesaji.mesaj !== '') {
        $(window).on('focus', function () {
            if (originalSiteTitle) {
                document.title = originalSiteTitle;
            }
        })
        $(window).on('blur', function () {
            var title = $('title').text();
            if (title !== siteSettings.pasifSekmeMesaji.mesaj) {
                originalSiteTitle = title;
            }
            document.title = siteSettings.pasifSekmeMesaji.mesaj;
        });
    }

    handlebarRegisterPartials();

    kampanyaBannerSayac();

    if (siteSettings.mobilUygulamaBilgileri != null && siteSettings.mobilUygulamaBilgileri.bannerAktif) {
        readySmartBanner();
    }

    if (siteSettings.magazaModulu != null && siteSettings.magazaModulu.magazaStokSatis.sayfadaGoster) {
        magazaStokSatisSayfadaGoster();
    }

    if ($("#scriptTemplateUrunSayfalama").length > 0) {


        $("body").on("click", ".detailUrl", function (e) {

            var product = e.target.closest('.productItem');
            var gaIndirimliFiyat = gaPriceEditCart($(product).find('.productPrice .discountPrice .discountPriceSpan').text());
            var gaSatisFiyat;
            if ($(product).find('.productPrice .regularPrice').length > 0) {
                gaSatisFiyat = gaPriceEditCart2($(product).find('.productPrice .regularPrice .regularPriceSpan').text());
                indirimTutar = gaSatisFiyat - gaIndirimliFiyat;
            } else {
                indirimTutar = 0;
                gaSatisFiyat = gaIndirimliFiyat;
            }

            var category = $(product).find('.productDetail')[0].dataset.category;
            var category1 = $(product).find('.productDetail')[0].dataset.category1;
            var category2 = $(product).find('.productDetail')[0].dataset.category2;
            var category3 = $(product).find('.productDetail')[0].dataset.category3;

            var dataLayerItems = [
                {
                    urunid: $(product).find('.productDetail').attr('data-variant-id'),
                    kartid: $(product).find('.productDetail').attr('data-id'),
                    urunName: $(product).find('.productName > a').text(),
                    urunMarka: $(product).find('.productMarka').text(),
                    urunKategori: category,
                    urunKategori1: category1,
                    urunKategori2: category2,
                    urunKategori3: category3,
                    position: parseFloat($(product).closest('.ItemOrj').attr('pushindex')),
                    tutar: gaIndirimliFiyat,
                    ilkTutar: gaSatisFiyat,
                    indirimOran: indirimTutar.toFixed(2),
                }
            ];
            var dataLayerTotalPrice = gaIndirimliFiyat;
            dataLayerPushEvent('select_item', dataLayerItems, dataLayerTotalPrice);

        });
    }

    if (siteSettings.sayfalamaSecenek == 2 || siteSettings.sayfalamaSecenek == 3) {

        $("body").on("click", ".detailUrl", function () {
            if (typeof productDetailModel == 'undefined') {
                var productCount = $('.ItemOrj').length;
                if (siteSettings.sayfalamaSecenek == 2) {
                    productCount += 20;
                }

                var thisPageNumber = $(this).closest('.productItem').find('.productDetail').attr('data-page');
                var cUrl = location.href.replace(location.origin, '');

                cUrl = removeURLParameter(cUrl, 'kayitsayisi');
                cUrl = removeURLParameter(cUrl, 'seciliurun');
                cUrl = cUrl + (cUrl.indexOf("?") === -1 ? "?" : "&");

                cUrl += "kayitsayisi=" + productCount;
                cUrl += "&seciliurun=" + parseInt(this.getAttribute("data-id"));

                if (cUrl.includes('sayfa=')) {
                    cUrl = cUrl.replace('sayfa=' + cUrl.split('sayfa=')[1].split('&')[0], 'sayfa=' + thisPageNumber);
                }

                //videoList.push({ Url: cUrl, ProductCount: productCount, ProductId: parseInt(this.getAttribute("data-id")) });
                // JSON.stringify(videoList)
                //window.ticimaxStorage.add("tcmx-page-history", JSON.stringify(videoList), true);
                SetVisitInfo(cUrl, null, cUrl);

                if (cUrl.includes('sayfa=')) {
                    urlSetPageNumber = cUrl.split('sayfa=')[0] + 'sayfa=' + cUrl.split('sayfa=')[1].split('&')[0];

                    history.pushState({ type: 1, path: urlSetPageNumber }, "", urlSetPageNumber);
                }
                if (typeof initUrunDetay != 'undefined') {
                    initUrunDetay();
                }
            }
        });

        //setTimeout(function () {
        //    if (getQueryStringByName("seciliurun")) {
        //        $("a[data-id='" + getQueryStringByName("seciliurun") + "']").attr("tabindex", -1).focus();
        //    }
        //}, 500);

    }

    if (getQueryStringByName("country") && globalModel.langModel.countryContainerActive) {
        TiciNoty.Show({ message: translateIt("Global_BolgeDegisiklikBilgi"), type: "info", autoclose: false });
    }

    if ((siteSettings.ticimaxStoryActive && document.getElementById("ticimaxStories") != null) || siteSettings.instagramStoryActive && document.getElementById("instaStories") != null) {
        function fncRunStories() {
            if (siteSettings.instagramStoryActive) {
                bindInstaStories();
            }
            if (siteSettings.ticimaxStoryActive && typeof bindTicimaxStories != 'undefined') {
                bindTicimaxStories();
            }
        }


        if (document.getElementById('linkZuck') == null) {
            loadStyle("Scripts/stories/zuck.min.css?v=" + siteSettings.yazilimVersiyon + "", function () { });
        }
        if (document.getElementById('scriptZuck') == null) {
            loadScript("Scripts/stories/zuck.js?v=" + siteSettings.yazilimVersiyon + "", function () {
                fncRunStories()
            });
        } else {
            fncRunStories()
        }
    }


    setTimeout(function () {
        if (siteSettings.siteYonetimAyar.urunListeImageSliderAktif || siteSettings.urunAyar.urunDetaySecenekGosterimTipi > 0) {
            productlistOwlCarousel();
            productlistChangeImage();
        }
    }, 100);
    $(".productItem video.notAutoPlay").on('play', function (e) {
        var productUnique = $(e.target).attr("data-productUnique");

        playProductVideo(null, productUnique, true);
        $('#urunListeVideoPlay_' + productUnique).html('<i class="fa fa-pause-circle-o" aria-hidden="true"></i>');
    });


    $("body").on("click", ".productItemV3 .urunSecenekSlider .detailLink", function (e) {
        e.preventDefault();
        var productId = parseInt($(this).attr("data-id"));
        var uniqueId = $(this).parents(".productItemV3").attr("data-unique");
        getProductListDetail(productId, uniqueId);
    });

    $("body").on("click", "#quickViewV2 .RightDetail .urunSecenekSlider .detailLink", function (e) {
        e.preventDefault();
        var productId = parseInt($(this).attr("data-id"));
        showQuickView(productId, true);
    });

    if (siteSettings.magazaModulu != null && siteSettings.magazaModulu.magazaStokSatis.aktif && siteSettings.magazaModulu.magazaStokSatis.bolgeSecimZorunlu && magazaBolgeSecimi == null) {
        window.store.showPopup(true);
    }

    setTimeout(function () {
        if (typeof prepareLangContainer !== "undefined") {
            prepareLangContainer();
        }
        else {
            top.prepareLangContainer();
        }
    }, 100);

    if (siteSettings.personaClickAktif) {
        setTimeout(function () {
            if (typeof personaclick !== 'undefined') {
                if (globalModel.member != null && globalModel.member.memberId > 0) {
                    var names = globalModel.member.memberName.split(" ");
                    var personaClickMemberData = {
                        id: globalModel.member.memberId,
                        email: globalModel.member.memberEMail,
                        first_name: names[0],
                        last_name: names.length > 1 ? names[1] : '',
                        phone: globalModel.member.memberGSMPhone,
                    };
                    if (globalModel.member.memberGender == 1) {
                        personaClickMemberData.gender = 'm';

                    } else if (globalModel.member.memberGender == 0) {
                        personaClickMemberData.gender = 'f';
                    }
                    if (globalModel.member.memberCountryCode != undefined && globalModel.member.memberCountryCode != null && globalModel.member.memberCountryCode != '') {
                        personaClickMemberData.location = globalModel.member.memberCountryCode;
                    }

                    personaclick('profile', 'set', personaClickMemberData);
                }
            }
        }, 700);
    }
    if ($('#scriptTemplateUrunSayfalama').length > 0) {
        itemCategoryAppend();
    }
    if (typeof customMobileFilterShow == 'undefined') {
        customMobileFilterShow = false;
    }
    if (customMobileFilterShow && isMobileDevice()) {
        itemFilterSetClick();
    }
    UpdateFavoriler();
});

function itemFilterSetClick() {
    $('.category-vertical-filters.top-filters .vertical-filter-panel').each(function () {
        $(this).find('.panel-heading > a.panel-title').attr("onclick", "setFilter(this, true, 'button')");
    });
}

function itemCategoryAppend() {
    var listIds = [];
    var items = [];
    $('.ItemOrj').each(function () {
        items.push($(this)[0]);
        var thisid = $(this).find('.productDetail').attr('data-id');
        listIds.push(parseInt(thisid));
    });
    productCategoryHierarchy('itemList', listIds, items);
}
$(document).on('scroll', function () {
    if ($('#scriptTemplateUrunSayfalama').length > 0) {
        ga4ViewItemList();
    }
});
var itemListga4 = [];
var itemListCount = 0;
function ga4ViewItemList() {
    setTimeout(function () {
        if ($('.ItemOrj').length > 0) {
            var firstInterval = document.documentElement.clientHeight + document.documentElement.scrollTop;
            $('.ItemOrj:not([pushGa="true"])').each(function () {
                if ($(this).find('.productDetail').length > 0) {
                    var lastInterval = document.documentElement.scrollTop - $('.ItemOrj').offset().top;
                    if ($(this).offset().top <= firstInterval && $(this).offset().top >= lastInterval) {
                        itemListga4.push($(this)[0]);
                        var thisid = $(this).find('.productDetail').attr('data-id');
                    }
                }
            });
        }

        if (itemListga4.length > 0) {
            if (globalModel.pageType == "search") {
                dataLayerPushEvent('search');
            }

            var itemListView = itemListga4.map(function (i) {
                $(i).attr('pushGa', 'true');
                if (!$(i).attr('pushIndex')) {
                    $(i).attr('pushIndex', itemListCount);
                }
                var kid = $(i).find('.productDetail').attr('data-id');
                var uid = $(i).find('.productDetail').attr('data-variant-id');
                var uname = $(i).find('.productName>a').text();
                var ubrand = $(i).find('.productMarka').text();
                var ucategory = $(i).find('.productDetail')[0].dataset.category;
                var ucategory1 = $(i).find('.productDetail')[0].dataset.category1;
                var ucategory2 = $(i).find('.productDetail')[0].dataset.category2;
                var ucategory3 = $(i).find('.productDetail')[0].dataset.category3;

                var gaIndirimliFiyat = gaPriceEditCart($(i).find('.productPrice .discountPrice .discountPriceSpan').text());
                var gaSatisFiyat;
                if ($(i).find('.productPrice .regularPrice').length > 0) {
                    gaSatisFiyat = gaPriceEditCart2($(i).find('.productPrice .regularPrice .regularPriceSpan').text());
                    indirimTutar = gaSatisFiyat - gaIndirimliFiyat;
                } else {
                    indirimTutar = 0;
                    gaSatisFiyat = gaIndirimliFiyat;
                }
                return {
                    urunid: uid,
                    kartid: kid,
                    urunName: uname,
                    urunMarka: ubrand,
                    urunKategori: ucategory,
                    urunKategori1: ucategory1,
                    urunKategori2: ucategory2,
                    urunKategori3: ucategory3,
                    indirimOran: indirimTutar.toFixed(2),
                    tutar: gaIndirimliFiyat,
                    ilkTutar: gaSatisFiyat,
                    position: itemListCount++
                };
            });

            dataLayerPushEvent('view_item_list', itemListView);
            itemListga4 = [];
        }
    }, 1000);
}
function productlistChangeImage(elem) {
    if (!elem) {
        var elem = $('.productSliderImage');
    }
    if (!isMobileDevice()) {
        $(elem).on('mousemove', function (e, t) {
            var i = this
                , n = $(e.currentTarget)
                , r = $(e.currentTarget).width()
                , o = n.closest(".productItem .productImageOwlSlider").find(".owl-item").not(".cloned").length
                , a = e.pageX - $(e.currentTarget).offset().left
                , s = r / o
                , c = Math.floor(a / s);
            c = c < 0 ? 0 : c,
                n.closest(".productItem .productImageOwlSlider").find(".owl-dot").eq(c).click();
        });
    }
}

$(window).on('load', function () {
    if (siteSettings.chromeBilgidirimAktif) {
        setTimeout(function () {
            $(".insider-opt-in-notification-title").text(function () { return $(this).text().replace("{alanadi}", window.location.hostname.replace("www.", "")); });
            $(".insider-opt-in-notification-description").text(function () { return $(this).text().replace("{alanadi}", window.location.hostname.replace("www.", "")); });
            var notySettings = TiciCookie.getObj('ticiPushNotification');
            if (isChrome && (!notySettings || notySettings === null) && !globalModel.isAndroidDevice && !globalModel.isiosDevice) {
                $(".bildirimIzin").slideDown("slow");
            }
            else if (isChrome && (notySettings && notySettings !== null && notySettings.chromePush)) {
                refrehsDeviceToken()
            }
        }, 100);
    }

    function refrehsDeviceToken() {
        var firebaseConfig;
        var publicKey;
        ticimaxApi.member.getFireBaseConfig(null, function (response) {
            firebaseConfig = response.config;
            publicKey = response.publicKey
        });
        const app = firebase.initializeApp(firebaseConfig);
        const messaging = firebase.messaging();
        messaging.getToken(messaging, { vapidKey: publicKey }).then((currentToken) => {
            if (currentToken) {
                var req = {
                    Token : currentToken
                };
                ticimaxApi.member.updateWebPushSubscriptionV1(req, function (response) { })
            }
            else {
                console.log('No registration token available. Request permission to generate one.')
            }
        })
    }

function retryWebPushSubscription(currentSub) {
    var vapidKey = "";
    ticimaxApi.member.getVapidKey(null, function (response) {
        vapidKey = response;
    });

    if (vapidKey !== "") {
        if ('serviceWorker' in navigator) {
            navigator.serviceWorker.register('/service-worker.js').then(function (e) {
            }).catch(function (error) {
                console.error('Service Worker Error', error);
            });
        } else {
            console.warn('Push servis desteklenmiyor!');
        }
        const applicationServerKey = urlB64ToUint8Array(vapidKey);

        navigator.serviceWorker.ready.then(function (serviceWorkerRegistration) {
            serviceWorkerRegistration.pushManager.subscribe({
                userVisibleOnly: true,
                applicationServerKey: applicationServerKey,
            }).then(function (subscription) {
                var updateWebPushSub = {
                    newPushSubscription: subscription.toJSON(),
                    currentPushSubscription: currentSub
                }
                ticimaxApi.member.updateWebPushSubscription(updateWebPushSub, function (response) {
                })
            }).catch(function (e) {
                console.log(e);
            });
        });
    }
}

if (isMobileDevice() && siteSettings.urunVideoAktif) {
    var blockFirstItem = $('.ProductList video.autoPlay').get(0);
    if (blockFirstItem != null) {
        blockFirstItem.play();
    }
}

    //setTimeout(function () {
    //    debugger
    //    if (typeof window.cart !== 'undefined') {
    //        window.cart.get.execute();
    //    }
    //    else {
    //        top.window.cart.get.execute();
    //    }
    //}, 100);
    //refreshSepet();
});

//function readySmartBanner() {

//    var script = document.createElement('script');
//    script.type = 'text/javascript';
//    script.src = '/Scripts/jquery/jquery.smartbanner/jquery.smartbanner.js';
//    script.onload = function () {
//        $.smartbanner(
//            {
//                icon: siteSettings.mobilUygulamaBilgileri.bannerLogo + '?v=1',
//                title: siteSettings.mobilUygulamaBilgileri.uygulamaBaslik,
//                author: siteSettings.mobilUygulamaBilgileri.author
//            });
//    };

//    document.getElementsByTagName('head')[0].appendChild(script);
//}

function readySmartBanner() {
    var link = document.createElement("LINK");
    link.setAttribute("rel", "stylesheet");
    link.setAttribute("type", "text/css");
    link.setAttribute("href", "/Scripts/jquery/jquery.smartbanner/smartbanner.min.css");

    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = '/Scripts/jquery/jquery.smartbanner/smartbanner.min.js';
    script.onload = function () {
        if (typeof smartbanner != 'undefined') {
            smartbanner.publish();
        }
    };

    document.getElementsByTagName('head')[0].appendChild(link);
    document.getElementsByTagName('head')[0].appendChild(script);

    //smartbanner| Header sticky oldugundaki durumuna gore
    $(window).on('load', function () {
        if ($('#header').css('position') == 'fixed') {
            setTimeout(function () {
                if ($('.smartbanner').length > 0) {
                    if ($(window).scrollTop() == 0) {
                        $('body').addClass('smartActive');
                    }
                }
                $(window).on('scroll', function () {
                    if ($('.smartbanner').length > 0) {
                        if ($(this).scrollTop() > $('.smartbanner').height()) {
                            $('body').removeClass('smartActive');
                        } else {
                            $('body').addClass('smartActive');
                        }
                    }
                });
            }, 100);
        } else if ($('#headerNew').length > 0) {
            setTimeout(function () {
                if ($('.smartbanner').length > 0) {
                    if ($(window).scrollTop() == 0) {
                        $('body').addClass('smartActive');
                    }
                }
                if ($('#masthead').css('position') == 'fixed') {
                    $(window).on('scroll', function () {
                        if ($('.smartbanner').length > 0) {
                            if ($(this).scrollTop() > $('.smartbanner').height()) {
                                $('body').removeClass('smartActive');
                            } else {
                                $('body').addClass('smartActive');
                            }
                        }
                    });
                }
            }, 100);
        }
        $(document).on('click', '.smartbanner__exit', function () {
            $('body').removeClass('smartActive');
        });
    });
}

function magazaStokSatisSayfadaGoster() {
    /*Anasayfa Kargo Satleri*/
    $("body").on("click", ".teslimatSaatiRow .teslimatSaatiCol", function () {
        var index = $(".teslimatSaatiRow .teslimatSaatiCol").index(this);
        $(".teslimatSaatiTabRow .satirTab").hide();
        $(".teslimatSaatiRow .teslimatSaatiCol").removeClass("active");
        $(this).addClass("active");
        $(".teslimatSaatiTabRow .satirTab:eq(" + index + ")").show();
    });
}

function bildirimRed() {
    $(".bildirimIzin").slideUp("slow");
    var notySettings = TiciCookie.getObj('ticiPushNotification') || {};
    notySettings.chromePush = false;
    TiciCookie.setObj('ticiPushNotification', notySettings, 365);
}

function bildirimKabul() {
    $(".bildirimIzin").slideUp("slow");
    var notySettings = TiciCookie.getObj('ticiPushNotification') || null;
    if (isChrome && (!notySettings || notySettings === null)) {
        var left = (screen.width / 2) - (400 / 2);
        var top = (screen.height / 2) - (400 / 2);
        window.open('https://' + window.location.hostname + '/BildirimIzin.aspx', '', 'width=400, height=400, left=' + left + ', top= ' + top + '');
    }
}

var teklifSorgulamaSiniri = 60;

var buSayfaPopup = null;
var popupKontrolTimer = 1000;
var popupKontrolSayisi = 0;
function AdminPopupControl() {
    var cookieValue = createTeklifCookie();
    var ilkZiyaret = new Date(cookieValue.ilkZiyaret);
    var sitedeGecirdigiSure = Math.round(((new Date()).getTime() - ilkZiyaret.getTime()) / 1000);
    var sayfadaGecirdigiSure = Math.round(((new Date()).getTime() - sayfayiIlkZiyaret.getTime()) / 1000);

    var popUpArgumanlari = {
        YonlendirenUrl: globalModel.urlReferrer,
        Url: window.location.pathname + window.location.search,
        SitedeGecirdigiSaniye: sitedeGecirdigiSure,
        SayfadaGecirdigiSaniye: sayfadaGecirdigiSure
    };

    popupKontrolleri(popUpArgumanlari);
}

function popupKontrolleri(request) {
    $.getJSON(siteSettings.storageLink + "/Uploads/popupTeklifler.json", { _: new Date().getTime() }, function (response) {
        var popuplar = response;
        popuplar = popuplar.filter(function (x) {
            return x.YonlendirenUrl === '' ? true : x.YonlendirenUrl === request.YonlendirenUrl;
        });
        popuplar = popuplar.filter(function (x) {
            return x.Url === request.Url;
        });
        popuplar = popuplar.filter(function (x) {
            return x.SitedeGecirdigiSaniye <= request.SitedeGecirdigiSaniye;
        });
        popuplar = popuplar.filter(function (x) {
            return x.SayfadaGecirdigiSaniye <= request.SayfadaGecirdigiSaniye;
        });
        popuplar = popuplar.filter(function (x) {
            return (new Date(x.BaslangicTarihi).getTime() < new Date().getTime()) && (new Date(x.BitisTarihi).getTime() > new Date().getTime());
        });
        popupKontrolSayisi++;
        if (popuplar.length > 0) {
            buSayfaPopup = popuplar[0];
            AdminPopupControlContent();
        } else {
            if (popupKontrolSayisi < teklifSorgulamaSiniri) {
                setTimeout(AdminPopupControl, popupKontrolTimer);
            }
        }
    });
}

function AdminPopupControlContent() {
    if (buSayfaPopup !== null) {

        var durum = createPopUpCookie(buSayfaPopup.ID);
        //alert(durum);
        if (durum) {
            $("#divAdminPopupText").html(buSayfaPopup.Icerik);
            $.fancybox($("#divAdminPopupContent").html());
        } else {
            if (popupKontrolSayisi < teklifSorgulamaSiniri) {
                setTimeout(AdminPopupControl, popupKontrolTimer);
            }
        }
    }
}

function createPopUpCookie(id) {

    var returnValue = true;

    var popupCookie = {
        GosterilenPopUp: []
    };

    if (TiciCookie.getObj('popupGosterim') !== null) {

        popupCookie = TiciCookie.getObj('popupGosterim');

        if (popupCookie.GosterilenPopUp.indexOf(id) < 0) {
            popupCookie.GosterilenPopUp.push(id);
            returnValue = true;
        }
        else {
            returnValue = false;
        }
    }
    else {
        popupCookie.GosterilenPopUp.push(id);
    }

    TiciCookie.setObj('popupGosterim', popupCookie, 365);
    return returnValue;
}

var mevcutTeklif = null;

var teklifKontrolTimer = 5000;
var teklifKontrolSayisi = 0;
function kampanyaTeklifleri(SayfadanCikis) {
    SayfadanCikis = SayfadanCikis || 0;

    var cookieValue = createTeklifCookie();
    var ilkZiyaret = new Date(cookieValue.ilkZiyaret);
    var sitedeGecirdigiSure = Math.round(((new Date()).getTime() - ilkZiyaret.getTime()) / 1000);
    var sayfadaGecirdigiSure = Math.round(((new Date()).getTime() - sayfayiIlkZiyaret.getTime()) / 1000);


    var teklifAramaArgumanlari = {
        YonlendirenUrl: globalModel.urlReferrer,
        Url: window.location.pathname,
        Kategori: null,
        SitedeGecirdigiSaniye: sitedeGecirdigiSure,
        SayfadaGecirdigiSaniye: sayfadaGecirdigiSure,
        UrunId: null,
        IlgilenmedigimTeklifler: cookieValue.ilgilenmedigimTeklifler,
        IlgilendigimTeklifler: cookieValue.ilgilendigimTeklifler,
        AtananTeklifler: cookieValue.atananTeklifler,
        CikisScript: SayfadanCikis
    };

    teklifleriKontrolEt(teklifAramaArgumanlari);
}

function teklifleriKontrolEt(request) {
    $.getJSON("/Uploads/kampanyaTeklifler.json", { _: new Date().getTime() }, function (response) {
        var teklifler = response;
        teklifler = teklifler.filter(function (x) {
            return x.YonlendirenUrl === '' ? true : x.YonlendirenUrl === request.YonlendirenUrl;
        });
        teklifler = teklifler.filter(function (x) {
            return x.Url === request.Url;
        });
        teklifler = teklifler.filter(function (x) {
            return x.CikisScriptAktif === request.CikisScript;
        });
        if (request.CikisScript !== 1) {
            teklifler = teklifler.filter(function (x) {
                return x.SitedeGecirdigiSaniye <= request.SitedeGecirdigiSaniye;
            });
            teklifler = teklifler.filter(function (x) {
                return x.SayfadaGecirdigiSaniye <= request.SayfadaGecirdigiSaniye;
            });
        }
        teklifler = teklifler.filter(function (x) {
            return (new Date(x.BaslangicTarihi).getTime() < new Date().getTime()) && (new Date(x.BitisTarihi).getTime() > new Date().getTime());
        });
        teklifler = teklifler.filter(function (x) {
            return request.IlgilendigimTeklifler.indexOf(x.ID) < 0 && request.IlgilenmedigimTeklifler.indexOf(x.ID) < 0 && request.AtananTeklifler.indexOf(x.ID) < 0;
        });
        teklifKontrolSayisi++;
        if (teklifler.length > 0) {
            mevcutTeklif = teklifler[0];
            teklifPopupGoster();
        } else {
            if (teklifKontrolSayisi < teklifSorgulamaSiniri) {
                setTimeout(kampanyaTeklifleri, teklifKontrolTimer);
            }
        }
    });
}

function teklifPopupGoster() {
    if (mevcutTeklif != null) {
        $("#divKampanyaTeklifText").html(mevcutTeklif.Icerik);
        $.fancybox($("#divKampanyaTeklifContent").html());
    }
}

function teklifPopupKapat() {
    $("#divKampanyaTeklifText").html("");
    $("#divKampanyaTeklifContent").hide();
    mevcutTeklif = null;
    $.fancybox.close();
}

function teklifKabul() {
    if (mevcutTeklif != null) {
        ticimaxApi.campaign.acceptOffer({ OfferId: mevcutTeklif.ID }, function (resp) {
            //Üye girişi yapmamışsa kampanya oluşturamaz.
            if (resp.kampanyaOlusturuldu) {
                kampanyaTeklifiAtandi(resp.teklifId);
            }
            else {
                kampanyaTeklifiIleIlgileniyorum(resp.teklifId);
            }
            teklifPopupKapat();
            setTimeout(kampanyaTeklifleri, teklifKontrolTimer);
        });
    }
}

function teklifRed() {
    if (mevcutTeklif != null) {

        kampanyaTeklifiIleIlgilenmiyorum(mevcutTeklif.ID);
        teklifPopupKapat();
        setTimeout(kampanyaTeklifleri, teklifKontrolTimer);
    }
}


function createTeklifCookie(newCookieValue) {
    var cookieValue =
    {
        ilkZiyaret: new Date(),
        ilgilenmedigimTeklifler: [],
        ilgilendigimTeklifler: [],
        atananTeklifler: [],
    };

    if (TiciCookie.getObjEncode('kampanyaTeklifleri')) {
        if (newCookieValue) {
            cookieValue = newCookieValue;
        } else {
            cookieValue.ilkZiyaret = new Date(TiciCookie.getObjEncode('kampanyaTeklifleri').ilkZiyaret);
            cookieValue.ilgilenmedigimTeklifler = TiciCookie.getObjEncode('kampanyaTeklifleri').ilgilenmedigimTeklifler ? TiciCookie.getObjEncode('kampanyaTeklifleri').ilgilenmedigimTeklifler : [];
            cookieValue.ilgilendigimTeklifler = TiciCookie.getObjEncode('kampanyaTeklifleri').ilgilendigimTeklifler;
            cookieValue.atananTeklifler = TiciCookie.getObjEncode('kampanyaTeklifleri').atananTeklifler;
        }
    }
    else if (newCookieValue) {
        cookieValue = newCookieValue;
    }

    var date = new Date();
    var minutes = 120;
    date.setTime(date.getTime() + (minutes * 60 * 1000));

    TiciCookie.setObj('kampanyaTeklifleri', cookieValue, 365);
    return TiciCookie.getObjEncode('kampanyaTeklifleri');
}

function kampanyaTeklifiIleIlgileniyorum(teklifId) {
    var newCookieValue = TiciCookie.getObjEncode('kampanyaTeklifleri');
    if (newCookieValue.ilgilendigimTeklifler.indexOf(teklifId) < 0)
        newCookieValue.ilgilendigimTeklifler.push(teklifId);
    createTeklifCookie(newCookieValue);
}

function kampanyaTeklifiIleIlgilenmiyorum(teklifId) {
    var newCookieValue = TiciCookie.getObjEncode('kampanyaTeklifleri');
    if (newCookieValue.ilgilenmedigimTeklifler.indexOf(teklifId) < 0)
        newCookieValue.ilgilenmedigimTeklifler.push(teklifId);
    createTeklifCookie(newCookieValue);
}

function kampanyaTeklifiAtandi(teklifId) {
    var newCookieValue = TiciCookie.getObjEncode('kampanyaTeklifleri');
    if (newCookieValue.atananTeklifler.indexOf(teklifId) < 0)
        newCookieValue.atananTeklifler.push(teklifId);
    createTeklifCookie(newCookieValue);
}

function clearTeklifCookie() {
    TiciCookie.remove("kampanyaTeklifleri");
}


function SosyalGirisKontrol() {
    var type = 0;
    var appName = getQueryStringByName("app");
    var loginCode = getQueryStringByName("code");
    var oauthToken = getQueryStringByName("oauth_token");
    var oauthVerifier = getQueryStringByName("oauth_verifier");
    var userName = "";
    var email = "";
    if (appName != null && appName.indexOf("apple") > -1) {
        loginCode = getCookie("AppleUserCode");
    }
    if (loginCode) {
        if (appName != null) {
            if (appName.indexOf("fb") > -1) {
                type = 1;
            } else if (appName.indexOf("mercan") > -1) {
                type = 4;
            } else if (appName.indexOf("apple") > -1) {
                var appleUserData = getCookie("AppleUser");
                var appleCode = getCookie("AppleUserCode");
                if (appleUserData != null && appleUserData != '') {
                    var userObj = JSON.parse(appleUserData);
                    userName = userObj.name.firstName + " " + userObj.name.lastName;
                    email = userObj.email;
                }

                loginCode = appleCode;
                type = 5;
            }
        } else {
            type = 3;
        }
    } else if (oauthToken) {
        type = 2;
    }
    if (type > 0) {
        ticimaxApi.member.socialLoginResult({ Type: type, LoginCode: loginCode, OauthToken: oauthToken, OauthVerifier: oauthVerifier, UserName: userName, Email: email }, function (response) {
            if (!response.isError) {
                var returnUrl = getCookie("socialLoginReturnUrl") ? decodeURIComponent(getCookie("socialLoginReturnUrl")) : "/";
                createCookie("socialLoginReturnUrl", "", -5);
                if (type == 4) {
                    localStorage.mercanLogin = true;
                }
                window.location.href = returnUrl;
            }
            else {
                TiciNoty.Show({ message: response.errorMessage, type: "warning" });
            }
        });
    }
}

function GetBlockModule(modulePageType) {
}

function ResetSliders() {
    $('.jCarouselLite ul').each(function () {
        var item = $(this);
        if (item.find('.owl-stage .owl-item').length > 0) {
            item.trigger('destroy.owl.carousel');
            var innerHtml = '';
            item.find('.owl-stage .owl-item').each(function () {
                innerHtml += $(this).html();
            });
            item.html(innerHtml).removeClass('owl-loaded').removeClass("owl-carousel");
        }
    });
    if (typeof urunListCallback != "undefined")
        urunListCallback();
}

function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0].toLowerCase()] = hash[1];
    }

    if (!vars["sayfa"]) {
        vars["sayfa"] = 1;
    }

    $('.ItemOrj').each(function () {
        $(this).find('.productDetail').attr('data-page', parseInt(vars["sayfa"]));
    });

    return vars;
}

function goToByScroll(elem) {
    $('html,body').animate({
        scrollTop: $(elem).offset().top
    }, 0);
}

function productsPageNumberAdd(products, page) {
    $.each(products, function (i, e) {
        $('.ItemOrj').each(function () {
            if (products[i].productId == $(this).find('.productDetail').attr('data-id')) {
                $(this).find('.productDetail').attr('data-page', page);
            }
        });
    });
}

var loadedProductCount = 0;

async function fncLoadCategoryProducts(source, template, response, filtreYenidenOlustur, htmlRender, productShowControl, elem) {

    if (productShowControl && !elem) {
        var sayfaNo = localStorage.getItem("gelinenSayfaNo");
        if (sayfaNo) {
            sayfaNo = parseInt(sayfaNo);
        }

        loadedProductCount += response.products.length;

        if (siteSettings.sayfalamaSecenek == 2 || siteSettings.sayfalamaSecenek == 3) {
            if (response.currentPage >= sayfaNo) {
                lastPageNumber = response.currentPage;
            }

            filterModel.paging.PageNumber = response.currentPage;
            if (sayfaNo) {
                if (sayfaNo > filterModel.paging.PageNumber) {
                    $('#ProductPageProductList').prepend("<div class='previousPageListBottom'></div>");
                    if (htmlRender) {
                        $('#ProductPageProductList').html(template(response));
                    } else {
                        $('#ProductPageProductList').prepend(template(response));
                    }
                    productsPageNumberAdd(response.products, filterModel.paging.PageNumber);

                    if (sayfaNo > filterModel.paging.PageNumber) {
                        goToByScroll($(".previousPageListBottom"));
                    }

                } else {
                    if (sayfaNo != filterModel.paging.PageNumber || sayfaNo == 1) {
                        if (htmlRender) {
                            $('#ProductPageProductList').html(template(response));
                        } else {
                            $('#ProductPageProductList').append(template(response));
                        }

                        productsPageNumberAdd(response.products, filterModel.paging.PageNumber);
                    }
                }
            } else {
                if (htmlRender) {
                    $('#ProductPageProductList').html(template(response));
                } else {
                    $('#ProductPageProductList').append(template(response));
                }

            }

            if (loadedProductCount > 0) {
                $('#divUrunYok').remove();
            }

            if (response.products.length === 0) {
                $('#divNextProduct').hide();
            }

            if (response.currentPage != 1) {
                categoryListProduct.push(response);
            }

            if (filterModel.paging.PageNumber === 1 && $("#oncekiUrunleriYukleBtnState")) {
                $("#oncekiUrunleriYukleBtnState").hide();
            }
        } else {
            $('#ProductPageProductList').html(template(response));
        }

        productsModel.newTransitionOrder = response.transitionOrder;
        if ($("#scriptTemplateUrunSayfalama").length > 0) {
            productLoadCompleted = true;
            if ((response.currentPage * response.productCountPerPage) >= response.totalProductCount) {
                $('#divNextProduct').hide();
            }
            else {
                $('.divNextProductCount').html(response.totalProductCount - (response.currentPage * response.productCountPerPage));
            }

            $(".categoryOverlay").hide();
            if ($(window).width() < 1025) {
                $(".mobilFilterOpenBtn").show();
            }

            var mappedProducts = Object.create(response.products).map(function (x) {
                return {
                    productId: x.productId,
                    name: x.name,
                    category: x.category,
                    brand: x.brand,
                    discountRate: x.discountRate,
                    price: x.productPriceOriginalStr,
                    sellPrice: x.productSellPriceStr,
                    categoryid: x.categoryId
                };
            });
            urunListeEntegrasyon(mappedProducts);
            var totalProductCount = response.totalProductCount;
            if (productsModel.transitionActive) {
                $(".FiltrelemeUrunAdet span").hide();
            }
            $(".FiltrelemeUrunAdet span").html(totalProductCount + " " + translateIt("GlobalMasterPage_SepetUrun"));
            if (typeof netTotalItems != "undefined") {
                netTotalItems = totalProductCount;
            }

            if (filtreYenidenOlustur) {
                await createFilterBlock(response.strProductIds, false, true);
            } else {
                if (productsModel.filterProductCountActive) {
                    await getFilterProductCounts();
                }
            }



            var productPerPage = response.productCountPerPage;
            if (totalProductCount > 0) {
                ProductPager = GetPager(totalProductCount, filterModel.paging.PageNumber, productPerPage);
                var source1 = $("#scriptTemplateUrunSayfalama").html();
                var template1 = Handlebars.compile(source1);
                var targetDiv = siteSettings.sayfalamaSecenek == 3 ? "#divSayfalamaAlt .pageNumber" : ".pageNumber";
                $(targetDiv).html(template1(ProductPager));
                if (ProductPager.currentPage == 1 && $('.ItemOrj').length == ProductPager.totalItems) {
                    $('.pageNumber').html("");
                }
            } else {
                $('.pageNumber').html("");
            }
        }
        initProductList();

        //var gelinenSayfaNo = parseInt(localStorage.getItem("gelinenSayfaNo"));
        //if (gelinenSayfaNo > 0 && gelinenSayfaNo < filterModel.paging.PageNumber) {
        //    changeUrlButNoReload(replaceQueryStringValue("sayfa", filterModel.paging.PageNumber));
        //}
    } else {
        if (filtreYenidenOlustur && productShowControl) {
            await createFilterBlock(response.strProductIds, elem, htmlRender);
        } else {
            if (productsModel.filterProductCountActive) {
                await getFilterProductCounts();
            }
        }
    }
    if (siteSettings.sayfalamaSecenek == 2) {
        setFilterUrl(filterModel, extraFilterObject.Sortings);
    }
}

var lastLoadedLowerPageNumber = 0;
var lastLoadedUpperPageNumber = 0;

function customFilterAccordion(elem) {
    if (!elem) {
        return;
    }
    var elClass = $(elem).closest('.panel')[0].className;
    var elActive = $(elem).closest('.panel').find('.panel-heading').hasClass('active');
    var elemClassName = elClass.replaceAll('more', ' ').replaceAll('More', ' ').replaceAll(' ', '');

    $('.category-vertical-filters.top-filters .panel .list-group').hide();
    $('.category-vertical-filters.top-filters .panel .panel-heading').removeClass('active');
    $('.category-vertical-filters.top-filters .panel').each(function (i, e) {

        var panelClassName = e.className.replaceAll('more', ' ').replaceAll('More', ' ').replaceAll(' ', '');

        if (panelClassName == elemClassName) {
            if (elActive) {
                $(this).find('.panel-heading').removeClass('active');
                $(this).find('.list-group').hide();
            } else {
                $(this).find('.panel-heading').addClass('active');
                $(this).find('.list-group').show();
            }
        }

    });
    $('body .loadingBarFilter').remove();
}
function getProducts(htmlRender, productShowControl, elem) {

    if (document.querySelector('.collectionDivShow')) {
        filterModel.filter.collectionId = document.querySelector('.collectionShowName').dataset.id;
    }
    if (typeof productShowControl == 'undefined') {
        productShowControl = true;
    }
    if (typeof elem == 'undefined') {
        elem = false;
    }

    if (siteSettings.sayfalamaSecenek == 2) {
        if (lastLoadedLowerPageNumber === 0 && lastLoadedUpperPageNumber === 0) {
            lastLoadedLowerPageNumber = filterModel.paging.PageNumber;
            lastLoadedUpperPageNumber = filterModel.paging.PageNumber;
        } else {
            if (filterModel.paging.PageNumber < lastLoadedLowerPageNumber) {
                lastLoadedLowerPageNumber = filterModel.paging.PageNumber;
            } else if (filterModel.paging.PageNumber > lastLoadedUpperPageNumber) {
                lastLoadedUpperPageNumber = filterModel.paging.PageNumber;
            } else if (filterModel.paging.PageNumber > lastLoadedLowerPageNumber && filterModel.paging.PageNumber < lastLoadedUpperPageNumber) {
                lastLoadedUpperPageNumber++;
                filterModel.paging.PageNumber++;
            }
        }
    }

    var source = $("#scriptTemplateUrunListesi").html();
    var template = Handlebars.compile(source);
    var filtreYenidenOlustur = productsModel.filterSettings != null ? productsModel.filterSettings.filtreyiYenidenOlusturAktif : false;
    initFilter(function () {
        ticimaxApi.product.getProductList({ FilterJson: JSON.stringify(filterModel.filter), PagingJson: JSON.stringify(filterModel.paging), CreateFilter: filtreYenidenOlustur, TransitionOrder: productsModel.transitionOrder, PageType: productsModel.pageType, PageId: productsModel.targetId }, function (response) {
            fncLoadCategoryProducts(source, template, response, filtreYenidenOlustur, htmlRender, productShowControl, elem)
        });
    });
}

//Ürünün Sepette Olup Olmadığını Gösterir
function InitInCart() {

    if (typeof ShowListProductInCart == "undefined") {
        return;
    }

    var cartList = [];
    if (typeof headerDesing != 'undefined') {
        $(".header-cart-hover .SProduct .topCardItem").each(function () {
            cartList.push(
                {
                    productId: parseInt($(this).find("input[name='hddProductId']").val()),
                    piece: parseFloat($(this).find(".SepetTopAdet").text().replace("x", ""))
                });
        });

    } else {
        $(".CartProduct .SProduct li").each(function () {
            cartList.push(
                {
                    productId: parseInt($(this).find("input[name='hddProductId']").val()),
                    piece: parseFloat($(this).find(".SepetTopAdet").text().replace("x", ""))
                });
        });
    }

    $(".productItem").each(function () {

        var btnAddToCart = $(this).find('.btnAddToCart');
        var productId = btnAddToCart.data('productid');

        var isProductCart = cartList.filter(function (el) {
            return el.productId == productId ? el : null;
        });

        if (isProductCart.length > 0) {
            var piece = 0;
            for (var i = 0; i < isProductCart.length; i++) {
                piece += isProductCart[i].piece;
            }
            btnAddToCart.text('(' + piece + ') ' + translateIt('UrunListesi_Sepette'));
            btnAddToCart.addClass("in-cart");
        }
        else {
            btnAddToCart.text(translateIt('UrunListesi_SepeteEkle'));
            btnAddToCart.removeClass("in-cart");
        }
    });

    if ($(".ProductDetailMain").length > 0) {


        var isProductCart = cartList.filter(function (el) {
            return el.productId == productDetailModel.productId ? el : null;
        });

        var btnAddToCart = $(".BasketBtn .basketBtn input");
        if (isProductCart.length > 0) {
            btnAddToCart.val('(' + isProductCart[0].piece + ') ' + translateIt('UrunListesi_Sepette'));
            btnAddToCart.addClass("in-cart");
        } else {
            btnAddToCart.val(translateIt('UrunListesi_SepeteEkle'));
            btnAddToCart.removeClass("in-cart")
        }

    }

}

function productListPrevPage(e) {
    e.preventDefault();
    if (filterModel.paging.PageNumber > 1) {
        ProductPager.setPage(filterModel.paging.PageNumber - 1);
        getProducts();
        backToTop();
        optimizeSeo(filterModel.paging.PageNumber - 1);
    }
}
function productListSetPage(e, page) {
    e.preventDefault();
    if (filterModel.paging.PageNumber != page) {
        filterModel.paging.PageNumber = page;
        getProducts();
        setFilterUrl(filterModel, extraFilterObject.Sortings);
        backToTop();
        optimizeSeo(page);
    }
    saveVisitPage();
}

function saveVisitPage() {
    var requestVisitPage = {
        FullPath: location.href,
        PathName: location.pathname,
        Search: location.search
    };
}

function productListNextPage(e) {
    e.preventDefault();
    if (filterModel.paging.PageNumber < ProductPager.totalPages) {
        ProductPager.setPage(filterModel.paging.PageNumber + 1);
        getProducts();
        backToTop();
        optimizeSeo(filterModel.paging.PageNumber);
    }
}

function GetProductItemClass() {
    if (globalBlokModel == 1) {
        return siteSettings.siteYonetimAyar.globalBlokModel1.urunListe;
    } else if (globalBlokModel == 2) {
        return siteSettings.siteYonetimAyar.globalBlokModel2.urunListe;
    } else if (globalBlokModel == 3) {
        return siteSettings.siteYonetimAyar.globalBlokModel3.urunListe;
    } else if (globalBlokModel == 4) {
        return siteSettings.siteYonetimAyar.globalBlokModel4.urunListe;
    }
};

function urunListeSepeteEkle(productId, variantId, kombin, kendinTasarla, hasVariants, asortiGroupId, stockAmount, url, redirectToDetail) {
    if (typeof kombin === "string") {
        kombin = kombin === "True";
    }
    if (typeof kendinTasarla === "string") {
        kendinTasarla = kendinTasarla === "True";
    }
    if (typeof hasVariants === "string") {
        hasVariants = hasVariants === "True";
    }
    if (typeof redirectToDetail === "string") {
        redirectToDetail = redirectToDetail === "True";
    }
    if (kombin || kendinTasarla || hasVariants || redirectToDetail) {
        window.location.href = url;
    } else {
        sepeteEkle(asortiGroupId > 0 ? 0 : variantId, stockAmount, 0, 0, asortiGroupId > 0 ? productId : 0, '', true, undefined, undefined, undefined, undefined, productId);
    }
}

function productListAddToCart(productId, variantId, asortiGroupId, stockAmount, url, redirectToDetail) {
    if (redirectToDetail === 1) {
        window.location.href = url;
    } else {
        sepeteEkle(asortiGroupId > 0 ? 0 : variantId, stockAmount, 0, 0, asortiGroupId > 0 ? productId : 0, '', true, undefined, undefined, undefined, undefined, productId);
    }
}

function productListAddToCartV2(unique, productId, variantId, assortmentProductId, piece, url, redirectToDetail, el) {
    if (redirectToDetail === 1) {
        window.location.href = url;
    } else {

        if (siteSettings.productListSelectVariantActive && variantId == 0) {
            listVariantModule.params.unique = unique;
            listVariantModule.params.productId = productId;
            listVariantModule.params.variantId = variantId;
            listVariantModule.params.variantId = variantId;
            listVariantModule.params.assortmentProductId = assortmentProductId;
            listVariantModule.params.piece = listVariantModule.params.piece > 0 ? listVariantModule.params.piece : piece;
            listVariantModule.params.url = url;
            listVariantModule.params.redirectToDetail = redirectToDetail;
            listVariantModule.bind(el);
        }
        else {
            var piece = parseFloat($('.txtSepetAdet' + unique).val().replace(",", "."));
            window.cart.add.model = window.cart.add.createModel();
            window.cart.add.model.productUnique = unique;
            window.cart.add.model.productId = productId;
            window.cart.add.model.variantId = variantId;
            window.cart.add.model.piece = piece;
            window.cart.add.model.assortmentProductId = assortmentProductId;
            window.cart.add.model.productUrl = url;
            window.cart.add.execute();
        }

    }
}


var productListFavorite = {};
productListFavorite.params = { element: null, unique: null, productId: null, variantId: null, piece: null, hasVariants: null, price: null };
productListFavorite.addRemove = function (element, unique, productId, variantId, piece, hasVariants, price) {
    productListFavorite.params.element = element;
    productListFavorite.params.unique = unique;
    productListFavorite.params.productId = productId;
    productListFavorite.params.variantId = variantId;
    productListFavorite.params.piece = piece;
    productListFavorite.params.hasVariants = hasVariants > 1;
    productListFavorite.params.price = price;
    //processType : 0 Çıkarma
    //processType : 1 Ekleme
    var processType = parseInt(element.getAttribute('data-action'));

    if (!globalModel.isAuthenticated) {

        if (siteSettings.uyeGirisPopupAktif) {
            window.mem.init.bind('login');
        }
        else {
            parent.window.location.href = "/UyeGiris?ReturnUrl=" + encodeURI(window.location.pathname);
        }

        return;
    }

    if (processType == 0) {

        var removeRequest = { GroupId: -1, FavoriteProductId: -1, ProductId: productId, VariantId: variantId };

        ticimaxApi.member.removeFavoriteGroupProduct(removeRequest, function (response) {
            UpdateFavoriler();
            callBackAddUrunListeFavori(productId, variantId, processType);

            if (typeof favoriUyariAktif == "undefined" ? true : favoriUyariAktif) {
                TiciNoty.Show({ message: translateIt('GlobalMasterPage_UyariFavoriCikarildi'), type: "warning" });
            }

            if (typeof visiLab !== "undefined") {
                visiLab.AddParameter("OM.pf", variantId);
                visiLab.AddParameter("OM.pfu", "-1");
                visiLab.AddParameter("OM.ppr", response ? parseFloat(response.salePrice).toFixed(2) : 0);
                visiLab.Collect();
                visiLab.SuggestActions();
            }

            if (siteSettings.personaClickAktif) {
                personaclick('track', 'remove_wish', productId);
            }
        });
    }
    else {
        if (hasVariants) {
            listVariantModule.params.unique = unique;
            listVariantModule.params.productId = productId;
            listVariantModule.params.variantId = variantId;
            listVariantModule.params.assortmentProductId = 0;
            listVariantModule.params.piece = piece;
            listVariantModule.params.url = '/';
            listVariantModule.params.redirectToDetail = false;
            listVariantModule.params.approveCallback = 'productListFavorite.Add';
            listVariantModule.bind();

        }
        else {
            productListFavorite.Add(element, unique, productId, variantId, piece, hasVariants, price);
        }

    }
}
productListFavorite.Add = function (element, unique, productId, variantId, piece, hasVariants, price) {
    if (element == null) {

        element = productListFavorite.params.element;
        unique = productListFavorite.params.unique;
        productId = productListFavorite.params.productId;
        variantId = productListFavorite.params.variantId;
        piece = productListFavorite.params.piece;
        hasVariants = productListFavorite.params.hasVariants;
        price = productListFavorite.params.price;
    }
    if (siteSettings.siteYonetimAyar.urunFavoriListeAktif) {
        $.get(siteSettings.siteYonetimAyar.sablonAyar.sablonYolu + "/Urun/UrunFavoriV2.html?v=" + siteSettings.yazilimVersiyon + "", function (data) {
            var compiled = Handlebars.compile(data);
            var favoriModel = {
                Type: 2,
                ProductId: productId,
                VariantId: variantId,
                Quantity: piece
            };
            createModal({
                id: "urunFavoriV2", content: compiled(favoriModel), width: '30%'
            });
        });
    }
    else {

        var reqAddToProduct = {
            GroupId: -1,
            ProductId: productId,
            VariantId: variantId,
            Quantity: piece
        };
        ticimaxApi.member.addFavoriteProduct(reqAddToProduct, function (response) {
            UpdateFavoriler();
            TiciDonusumKodlari.FacebookFavori(productId, price ? price : 0);
            callBackAddUrunListeFavori(productId, variantId, 1);
            if (typeof visiLab !== "undefined") {
                visiLab.AddParameter("OM.pf", variantId);
                visiLab.AddParameter("OM.pfu", "1");
                visiLab.AddParameter("OM.ppr", response ? parseFloat(response.salePrice).toFixed(2) : 0);
                visiLab.Collect();
                visiLab.SuggestActions();
            }

            if (siteSettings.personaClickAktif) {
                personaclick('track', 'wish', productId);
            }
        });

    }
}

function GetProductVariantImages(elem, productId, variantId, variantTypeValueId) {
    var parent = $(elem).parents(".productItem");
    var noStock = $(elem).hasClass("noStockProductList");
    if (!noStock) {
        ticimaxApi.product.getProductVariantImages({ ProductId: productId, VariantId: variantId }, function (response) {
            if (!response.isError && response.imagePath != null) {
                parent.find(".resimOrginal").attr("src", response.imagePath);
                if (typeof parent.find(".resimOrginal").attr("data-second") != "undefined") {
                    parent.find(".resimOrginal").attr("data-second", response.imagePath2);
                }
                var productUrl = parent.find(".productName a").attr("href");
                var qIndex = productUrl.indexOf('?');
                var href = qIndex > -1 ? productUrl.substr(0, qIndex) : productUrl;
                var finalHref = href + "?eksecenekid=" + variantTypeValueId;
                parent.find(".examineIcon a").attr("href", finalHref);
                parent.find(".productImage a").attr("href", finalHref);
                $(elem).attr("href", finalHref);
            }
        });
    }
}

var TicimxServerDate = new Date(globalModel.ttid);
setInterval(function () {
    TicimxServerDate.setSeconds(TicimxServerDate.getSeconds() + 1);
}, 1000);


function updateQueryStringParameter(uri, key, value) {
    var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
    var separator = uri.indexOf('?') !== -1 ? "&" : "?";
    if (uri.match(re)) {
        return uri.replace(re, '$1' + key + "=" + value + '$2');
    }
    else {
        return uri + separator + key + "=" + value;
    }
}

function SetVisitInfo(lastVisitPage, lastVisitProduct, visitCustomPage, isClearLocalStorage) {
    try {
        if (isClearLocalStorage) {
            localStorage.removeItem("lastVisitInfo");
        }

        var lastVisitInfo = {
            lastVisitPages: [],
            lastVisitProduct: [],
            lastVisitCustomPage: []
        };

        var local_Storage = localStorage.getItem('lastVisitInfo');
        if (local_Storage != null) {
            lastVisitInfo = JSON.parse(local_Storage);
        }

        if (lastVisitPage != null) {

            var lvPageUrl = typeof lastVisitPage == "object" ? lastVisitPage.href.replace(lastVisitPage.origin, "") : lastVisitPage; // Bu sekilde son adresi alıyoruz.
            if (lastVisitInfo.lastVisitPages.length > 0) {
                var lvPageLast = lastVisitInfo.lastVisitPages[lastVisitInfo.lastVisitPages.length - 1]; //Son kayıt mevcut sayfa ile aynı mı diye kontrol ediliyor. Burada arka tekrar eden kayıt olmasın diye
                if (lvPageLast != null && lvPageLast != lvPageUrl) {
                    lastVisitInfo.lastVisitPages.push(lvPageUrl);
                }
            }
            else {
                lastVisitInfo.lastVisitPages.push(lvPageUrl);
            }


        }

        if (lastVisitProduct != null) {

            var lvProductUrl = typeof lastVisitProduct == "object" ? lastVisitProduct.href.replace(lastVisitProduct.origin, "") : lastVisitProduct; // Bu sekilde son adresi alıyoruz.
            if (lastVisitInfo.lastVisitProduct.length > 0) {
                var lvProductLast = lastVisitInfo.lastVisitProduct[lastVisitInfo.lastVisitProduct.length - 1]; //Son kayıt mevcut sayfa ile aynı mı diye kontrol ediliyor. Burada arka tekrar eden kayıt olmasın diye
                if (lvProductLast != null && lvProductLast != lvProductUrl) {
                    lastVisitInfo.lastVisitProduct.push(lvProductUrl);
                }
            }
            else {
                lastVisitInfo.lastVisitProduct.push(lvProductUrl);
            }

        }

        if (visitCustomPage != null) {

            var lvCustomUrl = typeof visitCustomPage == "object" ? visitCustomPage.href.replace(visitCustomPage.origin, "") : visitCustomPage; // Bu sekilde son adresi alıyoruz.
            if (lastVisitInfo.lastVisitCustomPage.length > 0) {
                var lvCustomLast = lastVisitInfo.lastVisitCustomPage[lastVisitInfo.lastVisitCustomPage.length - 1]; //Son kayıt mevcut sayfa ile aynı mı diye kontrol ediliyor. Burada arka tekrar eden kayıt olmasın diye
                if (lvCustomLast != null && lvCustomLast != lvCustomUrl) {
                    lastVisitInfo.lastVisitCustomPage.push(lvCustomUrl);
                }
            }
            else {
                lastVisitInfo.lastVisitCustomPage.push(lvCustomUrl);
            }


            //lastVisitInfo.lastVisitCustomPage.push(visitCustomPage);
        }

        //Buradaki kontrol cok maxmiumum kayıt kontrolü için
        if (lastVisitInfo.lastVisitPages.length > 10) {
            lastVisitInfo.lastVisitPages = lastVisitInfo.lastVisitPages.slice(5, lastVisitInfo.lastVisitPages.length);
        }

        if (lastVisitInfo.lastVisitProduct.length > 10) {
            lastVisitInfo.lastVisitProduct = lastVisitInfo.lastVisitProduct.slice(5, lastVisitInfo.lastVisitProduct.length);
        }

        if (lastVisitInfo.lastVisitCustomPage.length > 10) {
            lastVisitInfo.lastVisitCustomPage = lastVisitInfo.lastVisitCustomPage.slice(5, lastVisitInfo.lastVisitCustomPage.length);
        }

        localStorage.setItem('lastVisitInfo', JSON.stringify(lastVisitInfo));
    } catch (e) {
        console.log("localStorage ayarlarını düzenleyin.");
        return {
            lastVisitPages: [],
            lastVisitProduct: [],
            lastVisitCustomPage: []
        };
    }

}

//Hersayfa localStorage ekleniyor.
SetVisitInfo(window.location, null, null);

function UpdateStokAlarm() {
    if (!globalModel.isAuthenticated) {
        return;
    }

    var localList = [];
    ticimaxApi.member.getStockAlertSummaryResponse({}, function (response) {
        for (var i = 0; i < response.stockAlerts.length; i++) {
            localList.push({
                productId: response.stockAlerts[i].productId,
                variantId: response.stockAlerts[i].variantId,
                stockAlertId: response.stockAlerts[i].stockAlertId,
                variantOptionId: response.stockAlerts[i].variantOptionId,
            });
        }
        SetStokBilgilendirme(localList);
    });
}

function IsFavoriControl(element, productId, variantId, tip) {
    var elem = $(element);
    if (!globalModel.isAuthenticated && tip == 1) {
        $(element).hide();
        return;
    }
    var favoriler = GetFavoriListe();
    if (favoriler.length > 0) {
        var filtered = favoriler.filter(function (x) {
            return x.productId == productId && x.variantId == variantId
        });
        if (filtered.length > 0 ? tip == 0 : tip == 1) {
            $(element).hide();
            return;
        }
    }
    else {
        if (tip == 1) {
            $(element).hide();
            return;
        }
    }
    $(element).show();
    return;
}

function getTeslimatSaatList(ilceID, semtID, kargoID) {
    ticimaxApi.content.getDeliveryTimeList({ CargoId: kargoID, DistrictId: ilceID, ZoneId: semtID }, function (response) {
        $.fancybox.open({
            type: "html",
            content: response.content
        });
    });
}

function kampanyaBannerSayac() {
    if ($('.Sayac').length > 0) {
        $('.Sayac').each(function () {
            kampanyaBannerSayacBaslat(this);
        });
    }
}

function kampanyaBannerSayacBaslat(elemnt) {
    var countDownDate = $(elemnt).attr("rel").toDateFromAspNet().getTime();
    var x = setInterval(function () {
        var now = new Date().getTime();
        var distance = countDownDate - now;
        var days = Math.floor(distance / (1000 * 60 * 60 * 24));
        var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);
        $(elemnt).html(days + " " + translateIt('Global_Gun').toLowerCase() + " " + hours + ":" + minutes + ":" + seconds)
        if (distance < 0) {
            clearInterval(x);
        }
    }, 1000);
}



if (siteSettings.urunVideoAktif && siteSettings.urunVideoEkranDisinaCikincaDurdur) {
    $(window).on('scroll', function () {
        var selectorItems = isMobileDevice() ? '.productItem video' : '.productItem video.notAutoPlay';
        $(selectorItems).each(function () {
            if (!$(this).is(":in-viewport")) {
                var videoItem = $(this).get(0);
                if (videoItem) {
                    videoItem.pause();
                    $(videoItem).trigger('pause');
                    $(videoItem).prop('currentTime', 0);
                    $(this).parent().parent().parent().find('.urunListeVideoPlay').html('<i class="fa fa-play-circle-o" aria-hidden="true"></i>');
                }
            }
        });
    });
}



//$(document).ready(function () {
//    $(".productItem video").on("onplay", function (e) {
//        var productUnique = $(e.target).attr('data-productUnique');
//        playProductVideo(null, productUnique);
//    });
//});


function playProductVideo(btnElement, _productId, disableVideoProcess) {
    try {
        var thisVideoElement = $('.urunVideo_' + _productId);
        var videoItem = thisVideoElement.get(0);

        var blockModuleId = parseInt(thisVideoElement.attr('data-blokmoduleid')) || 0;
        if (blockModuleId > 0) {

            //$('.ProductList video').trigger('pause');
            //$('.ProductList video').prop('currentTime', 0);

            $('.blockID-' + blockModuleId + ' video').not('.urunVideo_' + _productId).trigger('pause');
            $('.blockID-' + blockModuleId + ' video').not('.urunVideo_' + _productId).prop('currentTime', 0);
            $('.blockID-' + blockModuleId + ' .urunListeVideoPlay').html('<i class="fa fa-play-circle-o" aria-hidden="true"></i>');

            $('.blockID-' + blockModuleId + ' .productDetail').addClass('videoAutoPlayFalse').removeClass('videoAutoPlayTrue');
        }
        else if (typeof productsModel != 'undefined' && productsModel.autoPlayVideo == 0) {
            //Video durduruluyor. Yeni video baslatiliyor.
            //$('#ProductPageProductList video').trigger('pause');
            //$('#ProductPageProductList video').prop('currentTime', 0);
            $('#ProductPageProductList video').not('.urunVideo_' + _productId).trigger('pause');
            $('#ProductPageProductList video').not('.urunVideo_' + _productId).prop('currentTime', 0);
            $('#ProductPageProductList .urunListeVideoPlay').html('<i class="fa fa-play-circle-o" aria-hidden="true"></i>');
            $('#ProductPageProductList .productDetail').addClass('videoAutoPlayFalse').removeClass('videoAutoPlayTrue');
        }

        if (btnElement == null) {
            btnElement = $('#urunListeVideoPlay_' + _productId);
        }

        if (videoItem.paused) {
            if (!disableVideoProcess) {
                videoItem.play();
            }
            btnElement.innerHTML = '<i class="fa fa-pause-circle-o" aria-hidden="true"></i>';
        }
        else {
            btnElement.innerHTML = '<i class="fa fa-play-circle-o" aria-hidden="true"></i>';
            if (!disableVideoProcess) {
                videoItem.pause();
            }
        }



    } catch (e) {
        console.log("ERROR PLAY");
    }
}

function showQuickView(ProductId, refreshModal, liveShopping) {
    if (siteSettings.urunAyar.hizliBakisGorunumAyar.tip == 0 && !liveShopping) {
        var hizliBakisCompiledHtml;
        var hizliBakisAltAlanCompiledHtml;
        var productImages = [];

        $.get(siteSettings.siteYonetimAyar.sablonAyar.sablonYolu + "/Urun/HizliBakis.html?v=" + siteSettings.yazilimVersiyon + "", function (page_data) {
            hizliBakisCompiledHtml = Handlebars.compile(page_data);
            $.get(siteSettings.siteYonetimAyar.sablonAyar.sablonYolu + "/Urun/HizliBakisAltBolum.html?v=" + siteSettings.yazilimVersiyon + "", function (page_data) {
                hizliBakisAltAlanCompiledHtml = Handlebars.compile(page_data);

                window.FastPreview = {};
                window.FastPreview.Model = {};

                window.FastPreview.QuantityDown = function (element) {
                    azalt(element);
                    window.FastPreview.Model.product.quantity = parseFloat($('#txtHizliBakisAdet').val());
                };
                window.FastPreview.QuantityUp = function (element) {
                    artir(element);
                    window.FastPreview.Model.product.quantity = parseFloat($('#txtHizliBakisAdet').val());
                };

                window.FastPreview.AddToCart = function (btn, notify) {
                    notify = typeof notify != "undefined" ? notify : true;
                    var selectedVariant = null;
                    var product = window.FastPreview.Model.product;
                    if (product.variantTypes.length > 0) {
                        if (product.variantTypes.length == product.selectedVariantTypeValues.length) {
                            selectedVariant = product.variants.filter(function (x) {
                                return x.variantPropertyIDs.toString() === product.selectedVariantTypeValues.toString();
                            })[0];
                        } else {
                            window.FastPreview.VariantAlert(btn);
                        }
                    } else {
                        selectedVariant = GetCurrentVariant(product);
                    }
                    if (selectedVariant != null) {
                        //siteSettings.sepeteEkleSepeteYonlendir = false;
                        //siteSettings.urunSepetAtPopup = false;
                        var adet = parseFloat($('#txtHizliBakisAdet').val());
                        sepeteEkle(selectedVariant.variantId, adet, 0, 0, 0, "", false, null, 0, notify, false);
                    }
                };

                window.FastPreview.ThumbImageChange = function (thumbImage) {
                    window.FastPreview.Model.product.selectedImage = thumbImage;
                    $("#hizliBakis").html(hizliBakisCompiledHtml(window.FastPreview.Model));

                    if (typeof UrunHizliBakisCallback !== "undefined")
                        UrunHizliBakisCallback();
                };

                ticimaxApi.product.getProductPreview({ ProductId: ProductId }, function (res) {
                    var product = res.product;
                    var resimYokUfak = '/Scripts/images/resimyok_ufak.jpg';

                    if (siteSettings.siteYonetimAyar.farkliResimHazirlaniyorGorselAktif) {
                        resimYokUfak = '/Uploads/Images/resim-hazirlaniyor/ufak-' + siteSettings.siteDili + '.jpg';
                    }

                    product.selectedImage = product.productImages.length > 0 ? product.productImages[0].imagePath : resimYokUfak;
                    product.quantity = product.productQuantityBoxDefaultValue;
                    product.selectVariantTypes = [];
                    product.selectedVariantTypeValues = [];
                    productImages = product.productImages;

                    if (product.variantTypes.length > 0) {
                        product.selectVariantTypes.push({
                            index: 0,
                            listType: product.variantTypes[0].listType,
                            name: product.variantTypes[0].name,
                            order: product.variantTypes[0].order,
                            variantTypeId: product.variantTypes[0].variantTypeId,
                            selectVariantTypeValues: product.variantTypes[0].variantTypeValues
                        });
                    }

                    window.FastPreview.Model = {
                        settings: {
                            showBreadcrumb: false,
                            showProductNew: siteSettings.urunAyar.hizliBakisGorunumAyar.yeniUrunGoster && product.newProduct,
                            showBrand: siteSettings.urunAyar.hizliBakisGorunumAyar.markaGoster,
                            showBrandLogo: siteSettings.urunAyar.hizliBakisGorunumAyar.markaLogoGoster,
                            showShortDescription: siteSettings.urunAyar.hizliBakisGorunumAyar.onYaziGoster,
                            showSalesUnit: siteSettings.urunAyar.hizliBakisGorunumAyar.satisBirimiGoster,
                            showQuantityBox: true,
                            showAddFavorites: siteSettings.urunAyar.hizliBakisGorunumAyar.favorilereEkleGoster,
                            showProductTab: siteSettings.urunAyar.hizliBakisGorunumAyar.urunTabGoster,
                            showProductTabDescription: siteSettings.urunAyar.hizliBakisGorunumAyar.urunTabUrunOzelliklerGoster,
                            showRelatedProduct: siteSettings.urunAyar.hizliBakisGorunumAyar.ilgiliUrunGoster,
                            showSimilarProduct: siteSettings.urunAyar.hizliBakisGorunumAyar.benzerUrunGoster,
                            showEstimatedDeliveryTime: siteSettings.urunAyar.hizliBakisGorunumAyar.tahminiTeslimSuresiGoster,
                            showDiscountRate: siteSettings.urunAyar.hizliBakisGorunumAyar.indirimOraniGoster && product.discountRate > 0,
                            showStockCode: siteSettings.urunAyar.hizliBakisGorunumAyar.stokKoduGoster,
                            showDetailButton: siteSettings.urunAyar.hizliBakisGorunumAyar.detayaGitButonGoster,
                            showPriceToMember: (siteSettings.urunAyar.urunFiyatUyeGoster && !globalModel.isAuthenticated)
                        },
                        product: product,
                        relatedProducts: res.relatedProducts,
                        similarProducts: res.similarProducts
                    };

                    window.FastPreview.SetPrice(product);

                    window.FastPreview.SetVariantClass();

                    var hizliBakisHtml = hizliBakisCompiledHtml(window.FastPreview.Model);
                    var rootTemplate = "<div id='hizliBakis'>" + hizliBakisHtml + "</div>";

                    var hizliBakisAltHtml = hizliBakisAltAlanCompiledHtml(window.FastPreview.Model);
                    rootTemplate += "<div id='hizliBakisAltAlan'>" + hizliBakisAltHtml + "</div>";

                    $.fancybox.open(rootTemplate, {
                        width: 768,
                        autoHeight: true,
                        autoWidth: true,
                        beforeShow: function () {
                            $("body").css({ 'overflow-y': 'hidden' });
                        },
                        afterClose: function () {
                            $("body").css({ 'overflow-y': 'visible' });
                        }

                    });

                    if (typeof UrunHizliBakisCallback !== "undefined")
                        UrunHizliBakisCallback();

                    var mainVariant = product.variants.filter(function (x) {
                        return x.isMainVariant;
                    })[0];
                    window.FastPreview.Model.product.stockCode = mainVariant.stockCode;
                    window.FastPreview.FavoritesControl(product.productId, mainVariant.variantId);

                    if (window.FastPreview.Model.settings.showBreadcrumb) {
                        setTimeout(function () {
                            GetCategoryBreadCrumb();
                        }, 500);
                    }

                    if (typeof urunListCallback != "undefined")
                        urunListCallback();
                    if (typeof urunSliderBlok != "undefined")
                        urunSliderBlok();
                    setTimeout(function () {
                        PreviewSlider('#divHizliBakisIlgiliUrun');

                    }, 300);

                    if (typeof urunListCallback != "undefined")
                        urunListCallback();
                    if (typeof urunSliderBlok != "undefined")
                        urunSliderBlok();

                    setTimeout(function () {
                        PreviewSlider('#divHizliBakisBenzerUrun');
                    }, 300);

                    window.FastPreview.BindTahminiTeslimSuresi(GetCurrentVariant(product));

                    if ((typeof urunDetay_varyasyonSecili !== 'undefined' && urunDetay_varyasyonSecili) || siteSettings.urunAyar.urunDetayVaryasyonOtomatikSec) {
                        $(".divKombinEksecenekTipi .size_box").not(".nostok").first().click();
                    }


                });

                window.FastPreview.FavoritesControl = function (productId, variantId) {
                    var IsFavoriUrun = false;
                    if (globalModel.isAuthenticated) {
                        var favoriListesi = GetFavoriListe();
                        if (favoriListesi.length > 0) {
                            var filtered = favoriListesi.filter(function (x) {
                                return x.productId === productId && x.variantId === variantId;
                            });
                            IsFavoriUrun = filtered.length > 0;
                        }
                    }

                    $(IsFavoriUrun ? "#aHizliBakisFavoriCikar" : "#aHizliBakisFavoriEkle").show();
                    $(IsFavoriUrun ? "#aHizliBakisFavoriEkle" : "#aHizliBakisFavoriCikar").hide();
                };

                window.FastPreview.FavoritesAddRemove = function (btn, processType) {
                    if (!globalModel.isAuthenticated) {

                        if (siteSettings.uyeGirisPopupAktif) {
                            window.mem.init.bind('login');
                        }
                        else {
                            parent.window.location.href = "/UyeGiris?ReturnUrl=" + encodeURI(window.location.pathname);
                        }

                        //parent.window.location.href = " /UyeGiris.aspx?ReturnUrl=" + encodeURI(window.location.pathname);
                        return;
                    }

                    var selectedVariant = null;
                    var product = window.FastPreview.Model.product;
                    if (product.variantTypes.length > 0) {
                        if (product.variantTypes.length === product.selectedVariantTypeValues.length) {
                            selectedVariant = product.variants.filter(function (x) {
                                return x.variantPropertyIDs.toString() === product.selectedVariantTypeValues.toString();
                            })[0];
                        } else {
                            window.FastPreview.VariantAlert($('.hizliBakisSepeteEkle'));
                            return;
                        }
                    } else {
                        selectedVariant = GetCurrentVariant(product);
                    }


                    var adet = 1;
                    var urunId = selectedVariant.variantId;
                    var urunKartiId = selectedVariant.productId;

                    if (processType === 0) {

                        var reqRemoveFavoriteGroupProduct = {
                            GroupId: -1,
                            FavoriteProductId: -1,
                            ProductId: urunKartiId
                        };

                        ticimaxApi.member.removeFavoriteGroupProduct(reqRemoveFavoriteGroupProduct, function (response) {
                            UpdateFavoriler();

                            if (typeof favoriUyariAktif == "undefined" ? true : favoriUyariAktif) {
                                generateNotify(translateIt('GlobalMasterPage_UyariFavoriCikarildi'), "warning");
                            }


                            $("#aHizliBakisFavoriEkle").show();
                            $("#aHizliBakisFavoriCikar").hide();

                            if (typeof visiLab != "undefined") {
                                visiLab.AddParameter("OM.pf", urunKartiId);
                                visiLab.AddParameter("OM.pfu", "-1");
                                visiLab.AddParameter("OM.ppr", response ? parseFloat(response.salePrice).toFixed(2) : 0);
                                visiLab.Collect();
                                visiLab.SuggestActions();
                            }

                            if (typeof getFavoriGrup != "undefined") {
                                getFavoriGrup();
                            }

                        });

                    }
                    else {
                        ticimaxApi.member.getFavoriteGroup({ VariantId: -1 }, function (response) {
                            if (response.errorMessage == "Auth failed") {
                                TiciNoty.Show({ message: translateIt('GlobalMasterPage_UyeGirisiYapmalisiniz'), type: 'warning' });
                            }
                            else if (response.favoriteGroups.length > 0) {
                                var htmlTemplate = '<div id="divFastPreviewModal" class="galeri-modal" style="display:block;">';
                                htmlTemplate += '<div class="galeri-modal-content" id="divGaleriCropModalContent" style="width:400px">';
                                htmlTemplate += '<a href="#"  onclick="FastPreview.CloseFavoritesPopup()"><i class="fa fa-times"></i></a>';
                                for (var i = 0; i < response.favoriteGroups.length; i++) {
                                    var thisItem = response.favoriteGroups[i];
                                    htmlTemplate += "<div class='detayFavoriListItem'>" + thisItem.definition + "";
                                    htmlTemplate += "<button type='button' onclick='FastPreview.AddToProductFavorites(" + selectedVariant.productId + "," + selectedVariant.variantId + "," + thisItem.groupId + ")'>Ekle</button>";
                                    htmlTemplate += "</div>";
                                }
                                htmlTemplate += '</div>';
                                htmlTemplate += '</div>';

                                $('body').append(htmlTemplate);
                            } else {
                                window.FastPreview.AddToProductFavorites(selectedVariant.productId, selectedVariant.variantId, -1)
                            }
                        });
                    }
                };

                window.FastPreview.AddToProductFavorites = function (productId, variantId, groupId) {

                    var reqAddToProduct = {
                        GroupId: groupId,
                        ProductId: productId,
                        VariantId: variantId,
                        Quantity: window.FastPreview.Model.product.productQuantityBoxDefaultValue
                    };
                    ticimaxApi.member.addFavoriteProduct(reqAddToProduct, function (response) {

                        parent.UpdateFavoriler();

                        if (typeof visiLab !== "undefined") {
                            visiLab.AddParameter("OM.pf", productId);
                            visiLab.AddParameter("OM.pfu", "1");
                            visiLab.AddParameter("OM.ppr", response ? parseFloat(response.salePrice).toFixed(2) : 0);
                            visiLab.Collect();
                            visiLab.SuggestActions();
                        }

                        $("#aHizliBakisFavoriCikar").show();
                        $("#aHizliBakisFavoriEkle").hide();

                        window.FastPreview.CloseFavoritesPopup();


                        if (!siteSettings.urunAyar.favoriGrupsuzEkleme) {
                            TiciNoty.Show({ message: translateIt('GlobalMasterPage_UyariFavoriEklendi'), type: 'info' });
                        }

                    });

                };

                window.FastPreview.CloseFavoritesPopup = function () {
                    $("#divFastPreviewModal").remove();
                };

                window.FastPreview.SetVariantClass = function () {
                    var product = window.FastPreview.Model.product;
                    for (var k = 0; k < product.selectVariantTypes.length; k++) {
                        var variantType = product.selectVariantTypes[k];
                        for (var z = 0; z < variantType.selectVariantTypeValues.length; z++) {
                            var variantValue = variantType.selectVariantTypeValues[z];
                            variantValue.cssClass = "size_box " + (variantValue.stockAmount < 1 ? " nostok" : "") + (variantValue.selected ? " selected" : "");
                        }
                    }
                };

                window.FastPreview.BindTahminiTeslimSuresi = function (buUrun) {
                    if (buUrun.showEstimatedDeliveryTime) {
                        $('#hizliBakisTahminiTeslimatSuresi').show();

                        if (buUrun.estimatedDeliveryTimeSameDay) {
                            $('#spnHizliBakisTahminiTeslimSuresi').html(translateIt("Global_AyniGun"));
                        }
                        if (siteSettings.urunAyar.urunDetayAyar.tahminiTeslimSuresiGosterimTipi === 2) {
                            $('#spnHizliBakisTahminiTeslimSuresi').html(buUrun.estimatedDeliveryTimeDate);
                        }
                        else {
                            if (buUrun.estimatedDeliveryTime > 0) {
                                if (siteSettings.urunAyar.urunDetayAyar.tahminiTeslimSuresiGosterimTipi === 1) {
                                    $('#spnHizliBakisTahminiTeslimSuresi').html(buUrun.estimatedDeliveryTimeDate);
                                }
                                else {
                                    $('#spnHizliBakisTahminiTeslimSuresi').html(buUrun.estimatedDeliveryTime + ' ' + translateIt("Global_Gun"));
                                }
                            }
                        }
                    }
                    else {
                        $('#hizliBakisTahminiTeslimatSuresi').hide();
                    }

                };

                window.FastPreview.SelectVariant = function (id, valueId, index) {
                    var otoSec = false;
                    var lastVariant;
                    var nextIndex = index + 1;
                    var product = window.FastPreview.Model.product;
                    product.selectVariantTypes[index].selectVariantTypeValues.map(function (x) { x.selected = false; });
                    product.selectVariantTypes[index].selectVariantTypeValues.filter(function (x) { return x.variantTypeValueId === valueId; })[0].selected = true;
                    product.selectedVariantTypeValues.length = index;
                    product.selectedVariantTypeValues.push(valueId);
                    if (product.variantTypes.length > nextIndex) {
                        var variantTypeValues = [];
                        var variants = product.variants.filter(function (x) {
                            return x.variantPropertyIDs.slice(0, nextIndex).toString() === product.selectedVariantTypeValues.toString();
                        });
                        for (var i = 0; i < variants.length; i++) {
                            var variant = variants[i];
                            variantTypeValues.push({
                                colorCode: variant.variantPropertyDetail[nextIndex].colorCode,
                                image: variant.variantPropertyDetail[nextIndex].image,
                                name: variant.variantPropertyDetail[nextIndex].name,
                                order: variant.variantPropertyDetail[nextIndex].order,
                                stockAmount: variant.variantPropertyDetail[nextIndex].stockAmount,
                                variantId: variant.variantPropertyDetail[nextIndex].variantId,
                                variantTypeId: variant.variantPropertyDetail[nextIndex].variantTypeId,
                                variantTypeName: variant.variantPropertyDetail[nextIndex].variantTypeName,
                                variantTypeValueId: variant.variantPropertyDetail[nextIndex].variantTypeValueId
                            });
                        }
                        product.selectVariantTypes.length = nextIndex;
                        product.selectVariantTypes.push({
                            index: nextIndex,
                            listType: product.variantTypes[nextIndex].listType,
                            name: product.variantTypes[nextIndex].name,
                            order: product.variantTypes[nextIndex].order,
                            variantTypeId: product.variantTypes[nextIndex].variantTypeId,
                            selectVariantTypeValues: variantTypeValues.sort(function (a, b) {
                                return parseInt(a.order) - parseInt(b.order);
                            })
                        });

                        if ((typeof urunDetay_varyasyonSecili !== 'undefined' && urunDetay_varyasyonSecili) || siteSettings.urunAyar.urunDetayVaryasyonOtomatikSec) {
                            otoSec = true;
                        }

                    } else {
                        lastVariant = product.variants.filter(function (x) {
                            return x.variantPropertyIDs.toString() === product.selectedVariantTypeValues.toString();
                        })[0];
                        window.FastPreview.SetPrice(product, lastVariant);

                        window.FastPreview.Model.product.productImages = productImages.filter(function (x) {
                            return x.variantId === lastVariant.variantId || x.variantId == 0;
                        });

                        if (window.FastPreview.Model.product.productImages.length > 0) {
                            window.FastPreview.Model.product.selectedImage = window.FastPreview.Model.product.productImages[0].bigImagePath;
                        }
                        otoSec = false;
                    }
                    window.FastPreview.SetVariantClass();

                    if (typeof UrunHizliBakisEkSecenekCallback !== "undefined")
                        UrunHizliBakisEkSecenekCallback();

                    $("#hizliBakis").html(hizliBakisCompiledHtml(window.FastPreview.Model));
                    if (lastVariant) {
                        window.FastPreview.Model.product.stockCode = lastVariant.stockCode;
                        window.FastPreview.FavoritesControl(id, lastVariant.variantId);
                        window.FastPreview.BindTahminiTeslimSuresi(lastVariant);
                    }

                    if (otoSec) {
                        if ($(".divKombinEksecenekTipi").length > 0 && $(".divKombinEksecenekTipi").length != nextIndex) {
                            $(".divKombinEksecenekTipi").eq(nextIndex).find(".size_box").not(".nostok").first().click();
                        }
                    }
                };

                window.FastPreview.SetPrice = function (product, variant) {
                    variant = GetCurrentVariant(product, variant);
                    var numFormatSetting = {
                        currencySymbol: variant.currencyFormat.formatDescriptionShow ? variant.currency : variant.currencyFormat.symbol,
                        currencySymbolLocation: variant.currencyFormat.iconLocation,
                        decimalPlaces: variant.currencyFormat.salesDecimalDigital,
                        decimalChar: variant.currencyFormat.decimalSeparator
                    }

                    window.FastPreview.Model.product.price = variant.originalProductPrice.numFormat(numFormatSetting);
                    window.FastPreview.Model.product.sellingPrice = variant.sellingPrice.numFormat(numFormatSetting);
                    window.FastPreview.Model.product.discountRate = variant.discountRate;

                    window.FastPreview.Model.settings.showDiscountRate = siteSettings.urunAyar.hizliBakisGorunumAyar.indirimOraniGoster && variant.discountRate > 0;
                    window.FastPreview.Model.product.vatIncluded = variant.vatIncluded;
                    window.FastPreview.Model.product.vatIncludedPrice = (variant.originalProductPrice + variant.originalProductPriceVat).numFormat(numFormatSetting);
                    window.FastPreview.Model.product.vatIncludedSellingPrice = (variant.sellingPrice + variant.sellingPriceVat).numFormat(numFormatSetting);
                    $("#hizliBakis").html(hizliBakisCompiledHtml(window.FastPreview.Model));

                    window.FastPreview.BindTahminiTeslimSuresi(variant);
                };

                window.FastPreview.VariantAlert = function (elm) {
                    $("body").addClass("kombinurunsecbody");
                    $(".kombinurunsecbody .kombinContent .urunsecoverlay").fadeIn();
                    $(elm).parent().find("#divKombinUrunEkSecenek").addClass("kombinEksecenekUyari");
                    $(elm).parent().find("#divKombinUrunEkSecenek").append("<div class='tooltipp'>Lütfen Seçim Yapınız<i></i></div>");
                    $(".urunsecoverlay").click(function () {
                        $(".kombinContent #divKombinUrunEkSecenek").removeClass("kombinEksecenekUyari");
                        $(".urunsecoverlay").fadeOut();
                        $(".tooltipp").remove();
                        $("body").removeClass("urunsecbody");
                    });
                    $(".kombinurunsecbody #divKombinUrunEkSecenek").click(function () {
                        $(this).removeClass("kombinEksecenekUyari");
                        $(".urunsecoverlay").fadeOut();
                        $(".tooltipp").remove();
                        $("body").removeClass("urunsecbody");
                    });
                };

                window.FastPreview.QuantityChange = function (element) {
                    window.FastPreview.Model.product.quantity = parseFloat($(element).val());
                };

                function GetCurrentVariant(pProduct, pVariant) {
                    if (typeof pVariant != "undefined") {
                        return pVariant;
                    }
                    else {
                        var currentVariant = pProduct.variants.filter(p => p.isMainVariant == true)[0];
                        if (currentVariant != null && typeof currentVariant != "undefined") {
                            return currentVariant;
                        }
                        else {
                            return pProduct.variants[0];
                        }
                    }
                }

                function PreviewSlider(rootClass) {
                    $(rootClass + ' .jCarouselLite ul').each(function () {
                        if ($(this).find("li").length > 0 && !$(this).hasClass("owl-carousel"))
                            $(this).owlCarousel({
                                autoplay: false,
                                loop: true,
                                autoplayTimeout: 2000,
                                navClass: ['ProductListprev', 'ProductListnext'],
                                autoplaySpeed: 2000,
                                autoplayHoverPause: true,
                                margin: 30,
                                nav: true,
                                responsive: {
                                    0: {
                                        items: 2,
                                        nav: true,
                                        loop: false
                                    },
                                    768: {
                                        items: globalBlokModel == 1 ? 2 : globalBlokModel == 2 ? 2 : globalBlokModel == 3 ? 2 : globalBlokModel == 4 ? 2 : 2,
                                        nav: true,
                                        loop: false
                                    },
                                    992: {
                                        items: globalBlokModel == 1 ? 3 : globalBlokModel == 2 ? 3 : globalBlokModel == 3 ? 3 : globalBlokModel == 4 ? 3 : 3,
                                        nav: true,
                                        loop: false
                                    },
                                    1200: {
                                        items: globalBlokModel == 1 ? 3 : globalBlokModel == 2 ? 2 : globalBlokModel == 3 ? 3 : globalBlokModel == 4 ? 4 : 4,
                                        nav: true,
                                        loop: false
                                    }
                                }
                            });
                    });

                    setTimeout(function () {
                        InitTimers();
                    }, 1000);
                }

                function GetCategoryBreadCrumb() {
                    ticimaxApi.product.getProductCategoryBreadCrumb({ CategoryId: window.FastPreview.Model.product.categoryId }, function (response) {
                        $('#ulBreadcrumb').html(response.breadCrumb);
                    });
                }

            });
        });
    } else if (siteSettings.urunAyar.hizliBakisGorunumAyar.tip == 1 || liveShopping) {
        var modalClassName = '';
        if (liveShopping) {
            modalClassName = 'liveShopping'
        }
        //modal aç
        $("body").append("<div id='fake-modal' class='modal'></div>")
        ticimaxApi.product.getProductDetail({ ProductId: ProductId, IsQuickView: true }, function (response) {
            //modal kapa
            window.itemsV3List = [];
            $("#fake-modal").remove();
            var detaySource = getHandlebarTemplate("ticimax-HizliBakisV2");
            var detayTemplate = Handlebars.compile(detaySource);
            var detayHtml = detayTemplate(response.detail);
            if (refreshModal) {
                $("#quickViewV2 .modal-content-html").html(detayHtml);
            } else {
                createModal({
                    id: "quickViewV2",
                    className: modalClassName,
                    content: detayHtml,
                    width: "50%"
                });
            }
            window.productDetailModel = response.detailModel;
            window.quickView = {
                variants: response.detail.product.variantTypeValues,
                selectedVariantsIds: []
            };
            if (typeof initUrunDetay != 'undefined') {
                initUrunDetay('showQuickView');
            }
            //ResetSliders();
            if (typeof initUrunDetayCallback != 'undefined') {
                initUrunDetayCallback();
            }
            if (typeof UrunHizliBakisCallback !== "undefined")
                UrunHizliBakisCallback();
            if (typeof urunListCallback != "undefined")
                urunListCallback();
            if (typeof urunSliderBlok != "undefined")
                urunSliderBlok();
            if ((typeof urunDetay_varyasyonSecili !== 'undefined' && urunDetay_varyasyonSecili) || siteSettings.urunAyar.urunDetayVaryasyonOtomatikSec) {
                $("#divUrunEkSecenekV2 .ekSecenekGrup .ekSecenekValues").not(".nostok").first().click();
            }
            lazyLoad();

            $("#quickViewV2 #imgUrunResim").removeAttr("onclick");
        });
    }

}

function showSendGiftModal(element, productId, type) {

    $.get(siteSettings.siteYonetimAyar.sablonAyar.sablonYolu + "/Urun/HediyeIpucu.html?v=" + siteSettings.yazilimVersiyon + "", function (page_data) {

        var model = {
            image: '',
            productName: '',
            productId: productId
        };

        if (type == 0) {
            model.image = $(element).attr('data-image');
            model.productName = $(element).attr('data-name');
        }
        else {
            model.image = $('#imgUrunResim').attr('src');
            model.productName = productDetailModel.productName;
        }

        ticimaxApi.content.getConstantContent({ ContentId: 22 }, function (res) {
            model.content = res.constantContent != null ? res.constantContent.content : '';
            var html = Handlebars.compile(page_data)(model);
            createModal({
                id: "sendGiftModal",
                content: html,
                width: "50%"
            });
            if (typeof sendGiftModalCallback != 'undefined') {
                sendGiftModalCallback(model);
            }
        });

    });

}


function showUIBlock(_message) {
    $.blockUI({
        message: _message
    });
}

function hideUIBlock(_message) {
    $.unblockUI();
}


function showTabDetail(element, blockModuleId, tabGrupId, sekmeId, sekmeIndex) {

    var divAnasayfatab = $('#divAnasayfatab' + blockModuleId);

    divAnasayfatab.find(".ulHeadItem li").removeClass("tabUrunActive");
    divAnasayfatab.find(".divAnasayfaTabAlt").removeClass("tabUrunActive");
    divAnasayfatab.find(".ulHeadItem .ItemIndex" + sekmeIndex).addClass("tabUrunActive");
    divAnasayfatab.find("div.ItemIndex" + sekmeIndex).addClass("tabUrunActive");
    var isLoaded = $(element).attr("data-load") == "true";
    if (!isLoaded) {
        if (typeof window.ProductTab.ProductTemplate == "undefined") {
            $.get("/Templates/100/Bloklar/TabUrun.html", function (data) {
                window.ProductTab.ProductTemplate = data;

                //var settings = {
                //    listType: window.ProductTab.blockSettings.ListType
                //};

                //window.ProductTab.ProductTemplate = Handlebars.compile(window.ProductTab.ProductTemplate)(settings);


                BindProductTab(blockModuleId, tabGrupId, sekmeId, sekmeIndex);
            });
        }
        else {
            BindProductTab(blockModuleId, tabGrupId, sekmeId, sekmeIndex);
        }
        $(element).attr("data-load", true);
    }
}

function BindProductTab(blockModuleId, tabGrupId, sekmeId, sekmeIndex) {

    //Birden fazla tab olacağı için iligli model datasını buluyoruz.
    var model = window.ProductTab["Model" + blockModuleId];
    var sekme = model.filter(function (x) {
        return x.Id === sekmeId;
    })[0];
    var filterModel = createProductFilterModel();
    filterModel.filter = sekme.productFilter.Filter;
    filterModel.paging = sekme.productFilter.Paging;

    $('#divAnasayfatab' + blockModuleId + " .tabContent" + sekmeId).html(sekme.description);
    var targetDivId = "divTabProductContent" + blockModuleId + sekmeId;

    ticimaxApi.product.getProductList({ FilterJson: JSON.stringify(filterModel.filter), PagingJson: JSON.stringify(filterModel.paging) }, function (response) {

        response.block = {};
        response.block.listType = window.ProductTab.blockSettings.ListType;

        var template = Handlebars.compile(window.ProductTab.ProductTemplate);

        $('#' + targetDivId).html(template(response));
        setTimeout(function () {
            if (typeof urunListCallback != "undefined")
                urunListCallback();
        }, 100);
        if (siteSettings.uyeAyar.uyelikSistemiAktif) {
            $(".favoriteslist[init='false']").trigger('onload');
        }
    });
}


function setDeliveryCountry(countryCode, countryName) {
    location = updateQueryStringParameter(location.href, 'country', countryCode);
}

function searchDeliveryCountry() {
    var q = $('#txtHeaderSeciliUlke').val();
    if (q && q.length > 0) {
        $('.teslimatUlkeSecUl li').each(function () {
            if ($(this).text().indexOf(q) > -1 || $(this).text().toLowerCase().indexOf(q.toLowerCase()) > -1) {
                $(this).show();
            } else {
                $(this).hide();
            }
        });
    } else {
        $('.teslimatUlkeSecUl li').show();
    }
}

function bindInstaStories() {

    if (document.getElementById("instaStories") == null) {
        return;
    }

    ticimaxApi.content.getInstagramStories(null, function (res) {

        var storiesObject = [];

        for (var i = 0; i < res.stories.length; i++) {
            storiesObject.push({
                id: "99",               // story id
                photo: "/Uploads/Instagram/story_picture.png?v=" + new Date().getDate(), //res.profilePicture,            // story photo (or user photo)
                name: res.userName,             // story name (or user name)
                link: "",             // story link (useless on story generated by script)
                lastUpdated: "",      // last updated date in unix time format
                seen: false,          // set true if user has opened
                items: [              // array of items
                    {
                        id: res.stories[i].id,       // item id
                        type: res.stories[i].mediaType == "VIDEO" ? "video" : "photo",     // photo or video
                        length: 3,    // photo timeout or video length in seconds - uses 3 seconds timeout for images if not set
                        src: res.stories[i].mediaUrl,      // photo or video src
                        preview: res.stories[i].previewImage,  // optional - item thumbnail to show in the story carousel instead of the story defined image
                        link: res.stories[i].redirectUrl, //res.stories[i].postLink,     // a link to click on story
                        linkText: res.stories[i].shortDesc, // link text
                        time: Math.floor(new Date(res.stories[i].publishTime) / 1000),     // optional a date to display with the story item. unix timestamp are converted to "time ago" format
                        seen: false   // set true if current user was read
                    }
                ]
            });

        }

        var stories = new Zuck('instaStories', {
            backNative: false,
            previousTap: true,
            skin: "Snapgram",
            autoFullScreen: false,
            avatars: true,
            paginationArrows: true,
            list: false,
            cubeEffect: true,
            localStorage: true,
            stories: storiesObject,
            language: {
                unmute: 'Durdurmak için tıklayın',
                keyboardTip: 'Sonrakini görmek için boşluk tuşuna basın',
                visitLink: translateIt('Global_LinkiZiyaretEdin'),
                time: {
                    ago: 'önce',
                    hour: 'saat',
                    hours: 'saatler',
                    minute: 'dakika',
                    minutes: 'dakika',
                    fromnow: 'şu andan itibaren',
                    seconds: 'saniye',
                    yesterday: 'dün',
                    tomorrow: 'yarın',
                    days: 'gün'
                }
            }
        });

    })



}

function getRelatedProducts(productId, $this) {

    ticimaxApi.product.getRelatedProducts({ ProductId: productId }, function (response) {
        if (!response.isError) {
            if (siteSettings.urunAyar.urunListeIlgiliUrunuUrunKartindaGoster) {
                productListRelatedProductCB(response, $this);
            } else {
                var products = response.relatedProducts;
                var htmlStr = "<div class='divRelatedProductsPopup'><h3>" + translateIt("Urunler_IlgiliUrunler") + "</h3>";
                htmlStr += "<ul class='ulRelatedProducts'>";
                for (var i = 0; i < products.length; i++) {
                    var product = products[i];
                    htmlStr += "<li><a href='" + product.url + "'><img src='" + product.imageThumbPath + "' /><span>" + product.name + "</span></a></li>";
                }
                htmlStr += "</ul></div>";
                createModal({
                    id: "relatedProduct",
                    content: htmlStr,
                    width: "50%"
                });
            }
        }
    });
}

function productListRelatedProductCB(res, $th) {
    var isMobileWidth = document.documentElement.clientWidth;
    var mobileWidth = 768;
    if (res != null) {
        var maxShow = 4;
        var products = res.relatedProducts;
        var htmlStr = "<div class='divRelatedProductsMini' style='display:none;'>";
        htmlStr += "<div class='relatedProductsMiniTitle'>";
        if (isMobileWidth < mobileWidth) {
            htmlStr += "<div class='relatedProductsMiniText'><span>" + translateIt("IlgiliUrun_Farkli_Renk_Secenekleri") + " (" + products.length + ")</span></div>";
            htmlStr += "<div class='relatedProductsMiniClose' onclick='closeRelated()'><i class='fa fa-times'></i></div>";
        } else {
            htmlStr += "<div class='relatedProductsMiniText'><span>" + translateIt("IlgiliUrun_Farkli_Renk_Secenekleri") + "</span></div>";
            if ((products.length - maxShow) > 0) {
                htmlStr += "<div class='relatedProductsMiniMore' onclick='goToDetail(this)'><span class='countMiniMore'>" + (products.length - maxShow) + "</span><span> " + translateIt("IlgiliUrun_Renk_Daha") + "</span></div>";
            }
        }
        htmlStr += "</div>";
        if (isMobileWidth < mobileWidth) {
            htmlStr += "<ul class='ulRelatedProductsMini owl-carousel'>";
        } else {
            htmlStr += "<ul class='ulRelatedProductsMini'>";
        }

        for (var i = 0; i < products.length; i++) {
            var product = products[i];
            var errorUrl = 'this.onerror=null;this.src="/Scripts/images/resim-hazirlaniyor/' + siteSettings.siteDili + '.jpg"';
            if (isMobileWidth < mobileWidth) {
                if (product.imageList.length > 0) {
                    htmlStr += "<li><a href='" + product.url + "'><img src='" + product.imageList[0].imagePath + "' onerror=" + errorUrl + " /><span>" + product.name + "</span></a></li>";
                } else {
                    htmlStr += "<li><a href='" + product.url + "'><img src='" + product.imageThumbPath + "' onerror=" + errorUrl + " /><span>" + product.name + "</span></a></li>";
                }
            } else {
                if (i < maxShow) {
                    if (product.imageList.length > 0) {
                        htmlStr += "<li><a href='" + product.url + "'><img src='" + product.imageList[0].imagePath + "' onerror=" + errorUrl + " /><span>" + product.name + "</span></a></li>";
                    } else {
                        htmlStr += "<li><a href='" + product.url + "'><img src='" + product.imageThumbPath + "' onerror=" + errorUrl + " /><span>" + product.name + "</span></a></li>";
                    }
                }
            }
        }
        htmlStr += "</ul></div>";
    }

    if (isMobileWidth < mobileWidth) {
        $('body').append('<div class="RelatedProductsMiniShadow" onclick="closeRelated()"></div>');
        $('body').append(htmlStr);
        setTimeout(function () {
            autoResize.tick();
            $('.divRelatedProductsMini').show();
            $('.divRelatedProductsMini .ulRelatedProductsMini.owl-carousel').owlCarousel({
                margin: 10,
                nav: false,
                dots: false,
                autoWidth: true,
            });
        }, 250)

    } else {
        $($th).closest('.productItem').find('.productDetail').after(htmlStr);
        $($th).closest('.productItem').find('.divRelatedProductsMini').css('bottom', $($th).closest('.productItem').height() - $($th).closest('.productImage').height());
        $($th).closest('.productItem').find('.divRelatedProductsMini').show();

        $('body').on('mouseover', '.divRelatedProductsMini li a', function () {
            var thsImg = $(this).closest('.productItem').find('.productImage');
            var img = getImgSetImg(thsImg, 'over', this);
            if (img) {
                $(img).attr('src', img.src.replace(img.imgName, img.thisimgname))
            }
        });

        $('body').on('mouseleave', '.divRelatedProductsMini', function () {
            var thsImg = $(this).closest('.productItem').find('.productImage');
            var img = getImgSetImg(thsImg, 'leave');
            if (img) {
                $(img).attr('src', img.src.replace(img.imgName, img.thisimgname));
                $('.divRelatedProductsMini').remove();
            }
        });
    }
    setTimeout(() => {
        autoResize.tick();
    }, 250)
}

function getImgSetImg(ths, ctrl, $this) {
    var img;
    if (ths.length == 0) {
        return false;
    }
    if (ctrl == 'leave') {
        if ($(ths).hasClass('productImageOwlSlider')) {
            img = $(ths).find('.owl-item.active .detailUrl img')[0];
        } else {
            img = $(ths).find('.detailUrl img.resimOrginal')[0];
        }

        img.imgName = img.currentSrc;
        if ($(ths).hasClass('productImageOwlSlider')) {
            img.thisimgname = img.dataset.src;
        } else {
            if (typeof img.dataset.original != 'undefined') {
                img.thisimgname = img.dataset.original;
            } else {
                img.thisimgname = img.dataset.src;
            }
        }
    }
    if (ctrl == 'over') {

        var thisimgsrc = $($this).find('img').attr('src');
        if (thisimgsrc.search('resim-hazirlaniyor') > -1) {
            return false;
        }

        if ($(ths).hasClass('productImageOwlSlider')) {
            img = $(ths).find('.owl-item.active .detailUrl img')[0];
        } else {
            img = $(ths).find('.detailUrl img.resimOrginal')[0];
        }
        if (img.currentSrc.search('resim-hazirlaniyor') > -1) {
            img.imgName = img.currentSrc;
            img.thisimgname = thisimgsrc;
        } else {
            img.imgName = img.currentSrc;
            img.thisimgname = thisimgsrc;
        }
    }

    return img;
}

function closeRelated() {
    $('.divRelatedProductsMini').remove();
    $('.RelatedProductsMiniShadow').remove();
}

function goToDetail($t) {
    window.location.href = $($t).closest('.productItem').find('.detailUrl').attr('href');
}

function cancelThemePreview() {
    ticimaxApi.content.cancelThemePreview({}, function () {
        location = location.href;
    });
}

function productlistOwlCarousel(elem) {
    var owl = $(elem);
    owl.on('initialized.owl.carousel', function (e) {
        var targetSlide = e.target;
        $(targetSlide).trigger('refresh.owl.carousel')
        if ($(targetSlide).width() >= $(targetSlide).find('.owl-item').width() + 10 || $(targetSlide).width() <= $(targetSlide).find('.owl-item').width() - 10) {
            $(targetSlide).trigger('refresh.owl.carousel')
        }
    });
    owl.owlCarousel({
        loop: false,
        nav: false,
        margin: 0,
        items: 1,
        dots: true,
        animateOut: "fadeOut",
        animateIn: "fadeIn",
        autoplay: false,
        rewind: false,
        lazyLoad: true,
        responsive: {
            0: {
                mouseDrag: true,
                mouseNav: false,
            },
            1024: {
                mouseDrag: false,
                mouseNav: true,
            }
        }
    });
    owl.on('mouseleave', function (e) {
        stopOwlPropagation('.productList-Image-Owl');
        owl.trigger('to.owl.carousel', [0, 900]);
    });
    productlistChangeImage(elem);
}
/* Ürün liste resim slider başa döndürme */
function stopOwlPropagation(element) {
    jQuery(element).on('to.owl.carousel', function (e) { e.stopPropagation(); });
}

function initProductList(initSlider) {
    setTimeout(function () {
        if (typeof urunListCallback != "undefined") {
            urunListCallback();
        }
        InitInCart();
        isProductsLoaded = true;
        if (siteSettings.uyeAyar.uyelikSistemiAktif) {
            $(".favoriteslist[init='false']").trigger('onload');
        }
        lazyLoad();
        if (siteSettings.siteYonetimAyar.urunListeImageSliderAktif || initSlider) {
            productlistOwlCarousel();
            productlistChangeImage();
        }
    }, 100);
    setTimeout(function () {
        InitTimers();
    }, 1500);
}

function IsJson(value) {
    try {
        JSON.parse(value);
        return true;
    } catch (error) {
        return false;
    }
}

function ReturnJson(value) {
    let imageArray = value.split("http");
    imageArray.splice(0, 1);
    for (let index = 0; index < imageArray.length; index++) {
        imageArray[index] = "http" + imageArray[index];
    }
    return imageArray;
}

function accessoryListProductImage(el) {
    const accessoryimg = (IsJson(el.dataset.accessoryimgjson) ? JSON.parse(el.dataset.accessoryimgjson) : ReturnJson(el.dataset.accessoryimgjson));
    $(el).closest('.productAccessoryList').find('.accessoryBtn').removeClass('active');
    $(el).addClass('active');
    let productSliderImgList = $(el).closest('.productItem').find('.productList-Image-Owl');
    let productImgList = $(el).closest('.productItem').find('.productImage .resimOrginal');
    let basketBtn = $(el).closest('.productItem').find('.mycartIcon > .btnAddToCart');

    let dataUrl = el.dataset.url;
    let dataUKId = el.dataset.id;
    let dataVId = el.dataset.variantId;
    let datauniq = el.dataset.unique;
    $(basketBtn).attr('onclick', 'productListAddToCartV2(' + datauniq + ',' + dataUKId + ',' + dataVId + ',0,1,"' + dataUrl + '",0)');

    if (productSliderImgList.length > 0) {
        $(productSliderImgList).trigger('destroy.owl.carousel').removeClass('owl-loaded');
        $(productSliderImgList).html('');
        $.each(accessoryimg, function (key, data) {
            $(productSliderImgList).append('<div class="imageItem"><a href="' + dataUrl + '" data-id="' + dataUKId + '" title="' + $(el).attr('title') + '" class="detailLink detailUrl"><img class="productSliderImage" src="' + data + '" alt="' + $(el).attr('title') + '" ></a></div>');
        });

        if ($(productSliderImgList).find('.imageItem').length > 1) {
            productlistOwlCarousel(productSliderImgList);
        }
    } else {
        $.each(accessoryimg, function (key, data) {
            $(productImgList).attr('src', data).attr('data-original', data);
            if (siteSettings.urunAyar.urunListe2ResimAktif && key == 1) {
                $(productImgList).attr('data-second', data);
            }
        });
    }

}

function getProductListDetail(productId, uniqueId) {
    ticimaxApi.product.getProductListDetail({ ProductId: productId }, function (response) {
        var detaySource = getHandlebarTemplate("ticimax-urunItemV3");
        var detayTemplate = Handlebars.compile(detaySource);
        var detayHtml = detayTemplate(response.model);
        var detayObj = $(detayHtml);
        var newUniqueId = detayObj.attr("data-unique");
        $(".productItemV3[data-unique='" + uniqueId + "']").html(detayObj.html());
        $(".productItemV3[data-unique='" + uniqueId + "']").attr("data-unique", newUniqueId);
        initProductList(true);
    });
}

function productListVariantClick(thisObj) {
    var elem = $(thisObj);
    if ($(elem).closest('.ekSecenekGrup.nostok').length == 0) {
        var mainDiv = elem.parents("[element-variantSelection=1]");
        var id = parseInt(elem.attr("data-id"));
        var parentId = parseInt(elem.attr("data-parent-id"));
        var parent = mainDiv.find("[data-id=" + parentId + "]");
        var uniqueId = mainDiv.attr("data-unique");
        var variantId = 0;
        elem.parent().siblings().removeClass("selected");
        elem.parent().addClass("selected");
        var eksecenekContainer = parentId > 0 ? mainDiv.find(".eksecenekContainer[data-parent-id=" + parentId + "]") : mainDiv.find(".eksecenekContainer:eq(0)");
        eksecenekContainer.nextAll().remove();
        var productObject = mainDiv.attr("id") == "divUrunEkSecenekV2" ? window.quickView : window.itemsV3List.filter(function (x) {
            return x.productUnique == uniqueId;
        })[0];
        productObject.selectedVariantsIds = [];
        mainDiv.find(".ekSecenekGrup.selected").each(function () {
            productObject.selectedVariantsIds.push(parseInt($(this).attr("data-id")));
        });
        var variantElement = getVariantTypeValue(productObject.variants, productObject.selectedVariantsIds);
        variantElement.subVariantValues = variantElement.subVariantValues.sort(function (a, b) {
            return a.order - b.order;
        });
        var templateString = getHandlebarTemplate("ticimax-UrunVaryasyon");
        var template = Handlebars.compile(templateString);
        var html = template({ variants: variantElement.subVariantValues, parentId: id });
        eksecenekContainer.after(html);
        if (variantElement.subVariantValues.length < 2) {
            variantId = parseInt(elem.attr("data-variantId"));
            $($("[class='ekSecenekValues'][data-variantId=" + variantId + "]")).parent().addClass("selected")
        }
        $("[element-addToCart=1][data-unique='" + uniqueId + "']").attr("data-variantId", variantId);
    }
}

function getVariantTypeValue(list, idList) {
    var deger = null;
    var vvv = list.filter(function (x) {
        return x.variantTypeValueId == idList[0];
    })[0];
    if (vvv.subVariantValues.length > 0 && idList.length > 1) {
        var newIdList = [];
        for (var i = 1; i < idList.length; i++) {
            newIdList.push(idList[i]);
        }
        deger = getVariantTypeValue(vvv.subVariantValues, newIdList);
    } else {
        deger = vvv;
    }
    return deger;
}

function productListAddToCartV3(thisObj, asortiGroupId, url, redirectToDetail) {
    var elem = $(thisObj);
    var mainVariantId = parseInt(elem.attr("data-mainVariantId"));
    var variantId = parseInt(elem.attr("data-variantId"));
    var productId = parseInt(elem.attr("data-productId"));
    var uniqueId = elem.attr("data-unique");
    var stockAmount = GetControlValue('.txtSepetAdet' + uniqueId);
    var hasVariant = $("[element-variantSelection=1][data-unique='" + uniqueId + "']").length > 0;
    if (!hasVariant) {
        variantId = mainVariantId;
    }
    if (redirectToDetail === 1) {
        window.location.href = url;
    } else {
        if (variantId > 0 || !hasVariant) {
            sepeteEkle(asortiGroupId > 0 ? 0 : variantId, stockAmount, 0, 0, asortiGroupId > 0 ? productId : 0, '', true, undefined, undefined, undefined, undefined, productId);
        } else {
            alert("Varyasyon seçiniz");
        }
    }
}

var listVariantModule = {};
listVariantModule.params = {
    unique: '',
    productId: 0,
    variantId: 0,
    assortmentProductId: 0,
    piece: 0,
    url: '',
    approveCallback: ''
};
//listVariantModule.params.productId = 0;
//listVariantModule.params.unique = '';
listVariantModule.data = [];
listVariantModule.htmlTemplate = null;
listVariantModule.get = function (callback) {
    ticimaxApi.product.getProductVariantDetail({ productId: listVariantModule.params.productId }, function (response) {
        listVariantModule.data = response;
        if (callback) {
            callback();
        }
    });
};
var currentProductItem = null
listVariantModule.bind = function (el = null) {
    var pVariantDetail = $('.productItemVariantDetail');
    currentProductItem = $(el).closest('.productItem')
    pVariantDetail.html('');
    pVariantDetail.removeClass('active');

    currentProductItem.find('#productListVariantDetail' + listVariantModule.params.unique).addClass('active').html('');
    listVariantModule.get(function () {
        window['VariantValue0'] = listVariantModule.data;
        listVariantModule.render(listVariantModule.data);

        setTimeout(function () {
            if (listVariantModule.data.length == 1) {
                var thisObj = currentProductItem.find('#productListVariantDetail' + listVariantModule.params.unique + ' .ekSecenekValues');
                listVariantModule.setVariant(thisObj, listVariantModule.data[0].rootVariantTypeValueId, listVariantModule.data[0].variantTypeValueId);
            }
        }, 200);
    });
};
listVariantModule.render = function (variants) {
    if (listVariantModule.htmlTemplate == null) {
        listVariantModule.getTemplate(function (pageData) {
            listVariantModule.htmlTemplate = pageData;
            listVariantModule.RenderHandlebar(listVariantModule.htmlTemplate, variants);
        });
    }
    else {
        listVariantModule.RenderHandlebar(listVariantModule.htmlTemplate, variants);
    }
};
listVariantModule.RenderHandlebar = function (page_data, data) {
    var handlebarsCompile = Handlebars.compile(page_data);

    var model = {
        productUnique: listVariantModule.params.unique,
        variants: data,
        addCartButton: currentProductItem.find('#productListVariantDetail' + listVariantModule.params.unique + ' ' + '.btnVaryasyonSepeteEkle').length <= 0 && data.map(function (d) { return d.subVariantValues.length > 0 }).filter(function (x) { return x == true }).length <= 0
    };

    var templateHtml = handlebarsCompile(model);

    var selector = currentProductItem.find('#productListVariantDetail' + listVariantModule.params.unique);

    if (selector.find('.ekSecenek').length > 0) {
        selector.find('.ekSecenek').last().after(templateHtml);
    }
    else {
        selector.html(templateHtml);
    }
    selector.show();
};
listVariantModule.getTemplate = function (callBack) {
    $.get(siteSettings.siteYonetimAyar.sablonAyar.sablonYolu + "/Urun/UrunListeVaryasyon.html?v=" + siteSettings.yazilimVersiyon + "", function (page_data) {
        listVariantModule.htmlTemplate = page_data;
        if (callBack) {
            callBack(page_data);
        }
    });
};
listVariantModule.setVariant = function (thisObj, rootId, variantTypeValueId) {
    var selectedSecenekDiv = $(thisObj).parent();
    selectedSecenekDiv.find('.ekSecenekValues').removeClass('selected');

    selectedSecenekDiv.addClass('selected');
    $(thisObj).addClass('selected');

    if (typeof thisObj !== "undefined") {
        selectedSecenekDiv.nextAll().remove();
    }

    if (listVariantModule.data.length == 1) {
        if (listVariantModule.data[0].listType == 1) {
            $(thisObj).val(variantTypeValueId);
        }
    }

    var rootData = window['VariantValue' + rootId];
    if (typeof rootData != 'undefined') {
        var values = rootData.filter(function (x) {
            return x.variantTypeValueId == variantTypeValueId;
        });
        if (values.length > 0) {
            window['VariantValue' + variantTypeValueId] = values[0].subVariantValues;
            listVariantModule.render(values[0].subVariantValues);
        }

        var isRightScrollTopCalled = false;
        $('.miniCartLeftProduct').on('scroll', function (e) {
            if (isLeftScrollTopCalled) {
                return isLeftScrollTopCalled = false;
            }
            $('.miniCartRigthScroll').scrollTop($(this).scrollTop());
            isRightScrollTopCalled = true;
        });
    }
    var currentProductItem = $(thisObj).closest('.productItem');
    var selectedProductVariantDetail = currentProductItem.find('#productListVariantDetail' + listVariantModule.params.unique);
    var selectedLastVariantElement = selectedProductVariantDetail.find('.sonSecenek').find('.selected');

    if (selectedLastVariantElement.length > 0) {
        $('.btnVaryasyonSepeteEkle.button').hide();
        listVariantModule.approve(thisObj);
        //showLoading(true);
    }
}

listVariantModule.executeFunctionByName = function (functionName, context) {
    var args = Array.prototype.slice.call(arguments, 2);
    var namespaces = functionName.split(".");
    var func = namespaces.pop();
    for (var i = 0; i < namespaces.length; i++) {
        context = context[namespaces[i]];
    }
    return context[func].apply(context, args);
};

listVariantModule.approve = function (el = null) {

    var currentProductItem = $(el).closest('.productItem');
    var selectedProductVariantDetail = currentProductItem.find('#productListVariantDetail' + listVariantModule.params.unique);
    var selectedLastVariantElement = selectedProductVariantDetail.find('.sonSecenek').find('.selected');
    var selectedVariantId = parseInt(selectedLastVariantElement.attr('data-varintid')) || 0;
    if (selectedVariantId > 0) {

        if (listVariantModule.params.approveCallback != '') {
            productListFavorite.params.variantId = selectedVariantId;
            if (listVariantModule.params.approveCallback == "AddFavoriteProduct")
                listVariantModule.executeFunctionByName(listVariantModule.params.approveCallback, window, listVariantModule.params.processType, listVariantModule.params.productId, selectedVariantId, listVariantModule.params.piece);
            else
                listVariantModule.executeFunctionByName(listVariantModule.params.approveCallback, window, null);
        }
        else {
            window.cart.add.model = window.cart.add.createModel();
            window.cart.add.model.productUnique = listVariantModule.params.unique;
            window.cart.add.model.productId = listVariantModule.params.productId;
            window.cart.add.model.variantId = selectedVariantId;
            window.cart.add.model.piece = listVariantModule.params.piece;
            window.cart.add.model.assortmentProductId = listVariantModule.params.assortmentProductId;
            window.cart.add.model.productUrl = listVariantModule.params.url;
            window.cart.add.execute();
        }
        selectedProductVariantDetail.hide();
        selectedProductVariantDetail.html('');
        selectedProductVariantDetail.removeClass('active');
        listVariantModule.params.piece = 1;
    }
    else {
        TiciNoty.Show(translateIt('Validation_LutfenSecimYapin'))
    }
};

function GetProductVariantItemImages(elem, productId, url) {
    var parent = $(elem).parents(".productItem");

    let width = Math.floor($(parent).width());

    parent.find('.boxUrunResimContent').removeClass('active');
    parent.find('.boxUrunResimContent').parent().removeClass('active');
    $(elem).parent().addClass('active');
    $(elem).addClass('active');

    ticimaxApi.product.getProductImages({ ProductId: productId }, function (response) {
        if (!response.isError && response.productImages != null && response.productImages.length > 0) {

            if (window.autoResize.autoResizeRunningStatus) {
                for (let img of response.productImages) {
                    img.imagePath = window.autoResize.createUrl(img.imagePath, width, img);
                    img.thumbImagePath = window.autoResize.createUrl(img.thumbImagePath, width, img);
                    img.bigImagePath = window.autoResize.createUrl(img.bigImagePath, width, img);
                }
            }

            var productSliderImgList = parent.find(".productList-Image-Owl");
            var productImgList = parent.find(".productImage .resimOrginal");

            if (siteSettings.urunAyar.urunListeResimSliderAktif) {

                if (productSliderImgList.length > 0) {
                    $(productSliderImgList).html('');
                    var emptyImgListDiv = $(productSliderImgList);
                    $(productSliderImgList).remove();
                    parent.find('.productImage.productImageOwlSlider').prepend(emptyImgListDiv);
                    productSliderImgList = parent.find(".productList-Image-Owl");
                }

                $.each(response.productImages, function (key, data) {
                    if (productSliderImgList.length > 0) {
                        $(productSliderImgList).append('<div class="imageItem"><a href="' + url + '" data-id="' + data.productId + '" class="detailLink detailUrl"><img class="productSliderImage" src="' + data.thumbImagePath + '" ><\/a><\/div>');
                    } else {
                        if (key == 0) {
                            $(productImgList).attr('src', data.thumbImagePath).attr('data-original', data.thumbImagePath);
                        }
                        if (siteSettings.urunAyar.urunListe2ResimAktif && key == 1) {
                            $(productImgList).attr('data-second', data.thumbImagePath);
                        }
                        parent.find(".productImage a").attr("href", url);
                    }
                });

                if ($(productSliderImgList).find('.imageItem').length > 1) {
                    productlistOwlCarousel(productSliderImgList);
                }

            } else {

                $.each(response.productImages, function (key, data) {
                    if (key == 0) {
                        $(productImgList).attr('src', data.thumbImagePath).attr('data-original', data.thumbImagePath);
                    }
                    if (siteSettings.urunAyar.urunListe2ResimAktif && key == 1) {
                        $(productImgList).attr('data-second', data.thumbImagePath);
                    }
                });
                parent.find(".productImage a").attr("href", url);

            }

            parent.find(".examineIcon a").attr("href", url);
        }
    });
}

//if (window.location.pathname == "/") {
//    var unloadAction = 'beforeunload';
//    if (isSafari()) { unloadAction = 'pagehide'; }
//    window.addEventListener(unloadAction, function (e) {
//        var scrollPos = { url: "/", position: $(document).scrollTop() };
//        sessionStorage.setItem("homeScrollHistory", JSON.stringify(scrollPos));
//    });

//    if (sessionStorage["homeScrollHistory"]) {
//        var scrollPosition = JSON.parse(sessionStorage.getItem("homeScrollHistory"));
//        $(document).scrollTop(scrollPosition.position);
//    }
//}

$(document).on('click', '.blockSelect a', function () {
    //window.dispatchEvent(new Event('resize'));
    localStorage.setItem("productListingType", urunDuzeniTipi);


});

$(document).on('mouseenter', '.ResimliMenu1 li', function () {
    var imgBulk = $(this).find('img');
    $(imgBulk).each(function () {
        if (!$(this).hasClass('loaded')) {
            $(this).attr('src', $(this).attr('data-original'));
            $(this).addClass('loaded');
        }
    })
})

window.addEventListener("pageshow", function (evt) {
    if (evt.persisted) {
        window.cart.get.execute()
    }
}, false);

function urlB64ToUint8Array(base64String) {
    const padding = '='.repeat((4 - base64String.length % 4) % 4);
    const base64 = (base64String + padding)
        .replace(/\-/g, '+')
        .replace(/_/g, '/');

    const rawData = window.atob(base64);
    const outputArray = new Uint8Array(rawData.length);

    for (let i = 0; i < rawData.length; ++i) {
        outputArray[i] = rawData.charCodeAt(i);
    }
    return outputArray;
}

function collectionSaveData() {
    if (!globalModel.isAuthenticated) {

        if (siteSettings.uyeGirisPopupAktif) {
            window.mem.init.bind('login');
        }
        else {
            window.location.href = "/UyeGiris?ReturnUrl=" + encodeURI(window.location.pathname);
        }

        return;
    } else {
        var dataPost = {
            CollectionId: parseInt($('.collectionShowName')[0].dataset.id),
            MemberId: globalModel.member.memberId
        }

        ticimaxApi.collection.FollowedCollections(dataPost, function (response) {
            if (response.isError) {
                parent.TiciNoty.Show({ message: response.errorMessage, type: 'warning' });
            } else {
                parent.TiciNoty.Show({ message: translateIt('Message_IslerimizBasarili'), type: 'success' });
            }
        })
    }
}

function blogSearchFunction(event) {
    event.preventDefault();
    var query = document.getElementById('blogSearchInput').value;
    if (query) {
        window.location.href = '/blog?q=' + encodeURIComponent(query);
    }
}
if ($(window).width() < 767) { $('.blogSearchFormArea').prependTo('.blogCenter'); }