var HataDurum = false
var isStarted
var logs = ['Loglar']
var log = ''

var kontrol

var isRefreshed = false
var SekmeKapatildi = false
var PcName = ''

var AmazonUrl = ''
var AbeUrl = ''
var UrunID = ''
var MagazaAdi = ''
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
    if (message.Link) {
        window.location.reload()
        setTimeout(function () {
            window.location.reload()
        }, 1000)
    }
    if (message.UygulamaBaslatildi) {
        SekmeBilgileriGonder()
    }
    if (message.PageReload) {
        window.location.reload()
        setTimeout(function () {
            window.location.reload()
        }, 1000)
    }
    if (message.SekmeBulunamadi) {
        var text = "Extension'un çalıştığı sekme açık sekmeler arasında bulunamadı!"
        HataKontrolYap(1, text)
        console.log('Hata var:' + text)
    }
})

var linkKontrolCount = 0
var urunKontrolCount = 0

chrome.storage.onChanged.addListener(function (changes, namespace) {
    var storageChange

    for (key in changes) {
        if (key == 'KontrolUrl1' || key == 'KontrolUrl2') {
            storageChange = changes[key]
            if (storageChange.newValue.length > 0) {
                linkKontrolCount++
                //alert(linkKontrolCount);
                if (linkKontrolCount == 2) {
                    setTimeout(function () {
                        SiparisTamamla()
                    }, 2000)
                }
            }
        }
    }
})

$(document).ready(function () {
    var host = window.location.host
    chrome.storage.sync.get(
        [
            'isStarted',
            'UrunGetirildi',
            'Durum',
            'KontrolUrl1',
            'KontrolUrl1Hata',
            'KontrolUrl2Hata',
            'KontrolUrl2',
            'UrunFiyat',
            'AmzPageCount',
            'AbePageCount',
            'AmazonUrl',
            'AbeUrl',
            'UrunFiyat',
            'MagazaAdi',
            'RequestTime',
        ],
        function (item) {
            setTimeout(function () {
                if (item.isStarted == true) {
                    MagazaAdi = item.MagazaAdi
                    AmazonUrl = item.AmazonUrl
                    console.log(item.Durum)
                    AbeUrl = item.AbeUrl
                    var urll = window.location.href
                    if (urll == 'https://www.amazon.com/gp/errors/404.html') {
                        UrunZararYaz()
                    }
                    if (host == 'www.jqueryscript.net') {
                        if (item.UrunGetirildi == false) {
                            //KartBilgisiGetir(item.MagazaAdi);
                            UrunGetir()
                            SekmeBilgileriGonder()
                        } else if (item.KontrolUrl1.length > 0 && item.KontrolUrl2.length > 0) {
                            //UrlKontrolYap();
                            console.log('Ürün bilgisi alınmış. Şuan yapılan işlem: ' + item.Durum)
                            UrunGetir()
                            SekmeBilgileriGonder()
                        } else if (item.Durum == 'FiyatKontrol') {
                            console.log('Şuan yapılan işlem: ' + item.Durum)
                            UrunGetir()
                            SekmeBilgileriGonder()
                        } else {
                            console.log('düşün')

                            UrunGetir()
                            SekmeBilgileriGonder()
                        }
                    } else {
                        //HataKontrolYap(250);
                        if (item.Durum == 'TypeKontrol') {
                            var KontrolUrl1 = item.KontrolUrl1
                            var KontrolUrl2 = item.KontrolUrl2
                            var KontrolUrl1Hata = parseInt(item.KontrolUrl1Hata)
                            var KontrolUrl2Hata = parseInt(item.KontrolUrl2Hata)
                            var LinkKontrolSayfasi = parseInt(QueryStringOku('Validate'))
                            BirinciLinkKontrol(KontrolUrl2, KontrolUrl1Hata)
                            // setTimeout(function () {
                            // var TipKontrolYap = LinkKontrolSayfasi == 1 ? BirinciLinkKontrol(KontrolUrl2, KontrolUrl1Hata) : IkinciLinkKontrol(KontrolUrl1, KontrolUrl2Hata);
                            // }, 500);
                        } else if (item.Durum == 'FiyatKontrol') {
                            var Fiyat = item.UrunFiyat
                            var AmzPageCount = 0
                            var AbePageCount = 0
                            AmazonUrl = item.AmazonUrl
                            AbeUrl = item.AbeUrl
                            var FiyatKontrolSayfasi = QueryStringOku('PgNm')
                            if (FiyatKontrolSayfasi != null && FiyatKontrolSayfasi.length > 0) {
                                setTimeout(function () {
                                    var FiyatKontrolYap =
                                        FiyatKontrolSayfasi == 'Abe'
                                            ? AbeFiyatKontrol(Fiyat, AbePageCount, AbeUrl)
                                            : AmazonFiyatKontrol(Fiyat, AmzPageCount, AmazonUrl)
                                    console.log('FiyatKontrolYap')
                                }, 500)
                            }
                        } else if (item.Durum == 'UrunAl') {
                            AmazonUrl = item.AmazonUrl
                            AbeUrl = item.AbeUrl
                            var UrunSatinAlmaSayfasi = QueryStringOku('PgNm')
                            var UrunSepetSayfasi = QueryStringOku('Basket')
                            var AddAdres = QueryStringOku('AddAdres')
                            var AmzSepetBosalt = QueryStringOku('Sil')
                            var AbeBilling = QueryStringOku('Billing')
                            var isAbePlaceOrder = QueryStringOku('Complete')
                            if (UrunSatinAlmaSayfasi != null && UrunSatinAlmaSayfasi.length > 0) {
                                if (UrunSepetSayfasi != null && UrunSepetSayfasi.length > 0) {
                                    setTimeout(function () {
                                        var HangiSayfa = UrunSatinAlmaSayfasi == 'Abe' ? AbeBasketPage() : AmzBasketPage()
                                    }, 500)
                                } else if (AddAdres != null && AddAdres.length > 0) {
                                    setTimeout(function () {
                                        var HangiSayfa = UrunSatinAlmaSayfasi == 'Abe' ? AbeAdresSilme() : 'AmzAdresEkle()'
                                    }, 500)
                                } else if (AmzSepetBosalt != null && AmzSepetBosalt.length > 0) {
                                    setTimeout(function () {
                                        AmzBasketBosalt()
                                    }, 500)
                                } else if (AbeBilling != null && AbeBilling != 'false' && AbeBilling.length > 0) {
                                    setTimeout(function () {
                                        AbeEditBilling()
                                    }, 500)
                                } else if (isAbePlaceOrder != null && isAbePlaceOrder.length > 0) {
                                    setTimeout(function () {
                                        AbeOrderComplete()
                                        //incele
                                    }, 500)
                                } else {
                                    setTimeout(function () {
                                        var HangiSayfa = UrunSatinAlmaSayfasi == 'Abe' ? AbeUrunAl(item.UrunFiyat) : AmzUrunAl(item.UrunFiyat)
                                    }, 500)
                                }
                            } else if (window.location.href == 'https://www.abebooks.com/servlet/ShoppingBasket') {
                                AbeBasketBosalt()
                            } else if (window.location.href == 'https://www.abebooks.com/servlet/PaymentDetail?ac=f') {
                                AbeSaveBilling()
                            } else if (
                                window.location.href == 'https://www.abebooks.com/servlet/OrderSummary' &&
                                document.referrer == 'https://www.abebooks.com/servlet/PaymentDetail?ac=f'
                            ) {
                                AbeOrderComplete()
                            } else if (window.location.href == 'https://www.abebooks.com/servlet/ShippingAddress') {
                                var textMessage = $('.errorMessage').text()
                                if (textMessage.length > 0) {
                                    HataKontrolYap(1, textMessage.trim())
                                    console.log('Hata var:' + textMessage.trim())
                                    UrunZararYaz()
                                } else {
                                    //AbeAdresEkle();

                                    chrome.storage.sync.get(['AdresEklendi'], function (item) {
                                        console.log(item.AdresEklendi)
                                        if (!item.AdresEklendi) {
                                            var url = 'https://www.abebooks.com/servlet/ShippingAddress?AddAdres=true&PgNm=Abe'
                                            SayfaGit(url, 1)
                                        } else {
                                            var link = 'https://www.abebooks.com/servlet/OrderSummary?Billing=false&PgNm=Abe&Complete=true'
                                            SayfaGit(link, 1)
                                            console.log('Adres Eklendi && Sayfa Yenilendi')
                                        }
                                    })
                                }
                            } else if (window.location.pathname == '/gp/huc/view.html') {
                                var SepetCount = $('#nav-cart-count').text()
                                if (SepetCount != undefined && SepetCount.length > 0) {
                                    if (parseInt(SepetCount) > 1) {
                                        var amzlink = 'https://www.amazon.com/gp/cart/view.html?'
                                        var params = 'PgNm=Amz&Sil=True'
                                        var link = amzlink + params
                                        SayfaGit(link, 1)
                                    } else if (parseInt(SepetCount) == 1) {
                                        console.log('Sepetteki ürün 0')
                                        var amzlink = 'https://www.amazon.com/gp/cart/view.html?'
                                        var params = 'PgNm=Amz&Basket=True'
                                        var link = amzlink + params
                                        SayfaGit(link, 1)
                                    } else {
                                    }
                                }
                            } else if (window.location.pathname == '/gp/buy/addressselect/handlers/display.html') {
                                if ($('.address-book-title').length > 0) {
                                    location.reload()
                                }
                                AmzAdresEkle()
                            } else if (window.location.pathname == '/gp/yourstore') {
                                var SepetKargoAdres = 'https://www.amazon.com/gp/buy/addressselect/handlers/display.html'
                                // SekmeAc(SepetKargoAdres);
                                console.log('yourstore')
                            } else {
                                var path = window.location.pathname.toString()
                                var NotAdded = 'item-dispatch'
                                var NotAddedDurum = path.indexOf(NotAdded) !== -1
                                if (NotAddedDurum) {
                                    AmzItemNotAdded()
                                } else {
                                    var pass = $('.auth-text-truncate:first-child').text().trim().toLowerCase() + '478965'
                                    $('#ap_password').val(pass)
                                    if ($('#signInSubmit').length > 0) {
                                        $('#signInSubmit').click()
                                        $('#signInSubmit').trigger('click')
                                    } else UrunAl(1)
                                    console.log('hiç biri')
                                }
                            }
                        } else if (item.Durum == 'SiparisTamamla') {
                            var Sayfa = QueryStringOku('PgNm')
                            var SiparisTamamla = QueryStringOku('SiparisTamamla')
                            if (Sayfa != null && Sayfa.length > 0) {
                                if (SiparisTamamla != null && SiparisTamamla.length > 0) {
                                    setTimeout(function () {
                                        var HangiSayfa = Sayfa == 'Abe' ? AbeSiparisTamamla() : 'AmzSiparisTamamla()'
                                    }, 500)
                                }
                            } else if (window.location.pathname == '/servlet/ThankYou') {
                                // var params = "?PgNm=Abe&SiparisTamamla=True";
                                // var url = "https://www.abebooks.com/servlet/BuyerOrderTrackPL"
                                // var link = url + params;
                                // SayfaGit(link, 1);
                                // } else if (window.location.pathname == "/gp/buy/thankyou/handlers/display.html") {

                                if ($('.mfa-failure').length > 0) {
                                    chrome.storage.sync.set(
                                        {
                                            Durum: 'UrunAl',
                                            AdresEklendi: true,
                                        },
                                        function () {
                                            console.log('Siparişler alınacak. ')
                                            UrunAl(0)
                                        }
                                    )
                                    //UrunAl();//UrunZararYaz();
                                } else {
                                    AbeSiparisTamamla()
                                }
                            } else if (window.location.pathname == '/gp/buy/thankyou/handlers/display.html') AmzSiparisTamamla()
                        }
                    }
                }
            }, parseInt(item.RequestTime) * 1000)
        }
    )
})

function SiparisTamamla(dataArray) {
    var host = window.location.host
    if (host == 'www.jqueryscript.net') {
        chrome.storage.sync.get(['UrunID', 'PcName', 'Price', 'Review', 'Rating', 'brokenlink', 'rank', 'Stock'], function (item) {
            //MTip: Mağaza Tip (Amazon (0), Abe (1))

            var datam = {
                ID: item.UrunID,
                setdata: '1',
                price: item.Price,
                review: item.Review,
                rating: item.Rating,
                brokenlink: item.brokenlink,
                rank: item.rank,
                extension_name: item.PcName,
                stock: item.Stock ?? true,
            }
            console.log(datam)
            $.ajax({
                type: 'post',
                url: 'https://www.ecompricetracking.com/api/setProductData',
                beforeSend: function (xhr) {
                    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
                },
                cache: false,
                dataType: 'json',
                data: datam,
                success: function (cevap) {
                    console.log(cevap)
                    if (cevap.hata == '0') {
                        console.log('Hata: Sipariş Bilgileri Gönderilemedi!')
                        SekmeKapat(2)
                        //Hata alındı bilgilendirilme yapılacak
                    } else {
                        if (cevap.result == '1') {
                            console.log(cevap.result)
                            console.log('Sipariş bilgileri gönderildi')
                            var host = window.location.host
                            if (host == 'www.amazon.com' || host == 'www.abebooks.com') {
                                SekmeKapat(2)
                            }
                            setTimeout(function () {
                                UrunGetir()
                            }, 2000)
                        } else {
                            console.log('else girdi')
                        }
                    }
                    console.log('Sipariş Tamamla Response!')
                },
                error: function (req, textStatus, errorThrown) {
                    console.log('Ooops, something happened: ' + textStatus + ' ' + errorThrown)
                    SiparisTamamla()
                },
            })
        })
    }
}

var RunCount = 0
function UrunGetir() {
    var host = window.location.host
    if (host == 'www.jqueryscript.net') {
        chrome.storage.sync.set({
            KontrolUrl1: '',
            KontrolUrl2: '',
            Titles: '',
            Price: '',
            Review: '',
            Rating: '',
            brokenlink: '',
            rank: '',
        })
        var host = window.location.host
        setTimeout(function () {
            chrome.storage.sync.get(['MagazaAdi', 'isStarted'], function (item) {
                if (item.isStarted == true) {
                    clearTimeout(HataKontrol)
                    HataKontrolYap(250)
                    console.log('Ürün Getirilecek!')
                    localStorage.clear()
                    localStorage.removeItem('LSAmazonUrunList')
                    var datam = {
                        getdata: '1',
                    }
                    console.log(datam)
                    console.log('Ürün getirilecek!')
                    $.ajax({
                        type: 'post',
                        url: 'https://www.ecompricetracking.com/api/getProductData',
                        beforeSend: function (xhr) {
                            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
                        },
                        cache: false,
                        dataType: 'json',
                        data: datam,
                        success: function (cevap) {
                            console.log(cevap)
                            if (cevap.hata == 0 || cevap.data == null) {
                                chrome.storage.sync.set(
                                    {
                                        UrunGetirildi: false,
                                        Durum: 'AppStarted',
                                    },
                                    function () {
                                        console.log('Hata: Ürün getirilemedi!')
                                        var d1 = new Date(),
                                            d2 = new Date(d1)
                                        d2.setMinutes(d1.getMinutes() + 30)
                                        var sure = d2.toLocaleString().substring(11, 19)
                                        var text =
                                            ' Kontrol edilecek sipariş kalmadı! Uygulama 30 dk bekletiliyor.' +
                                            sure +
                                            ' itibariyle tekrar başlatılacak.'
                                        clearTimeout(HataKontrol)
                                        HataKontrolYap(1, text)
                                        chrome.runtime.sendMessage({
                                            YenidenBaslat: true,
                                        })
                                        if (host == 'www.amazon.com' || host == 'www.abebooks.com') {
                                            SekmeKapat(2)
                                        }
                                    }
                                )
                            } else {
                                if (cevap.data) {
                                    console.log(cevap.data)
                                    //console.table(cevap.result);
                                    var data = cevap.data
                                    if (true) {
                                        chrome.storage.sync.set(
                                            {
                                                UrunID: data.ID,
                                                UrunGetirildi: true,
                                                Durum: 'TypeKontrol',
                                                KontrolUrl1: '',
                                                KontrolUrl2: '',
                                                Url: data.ProductURL,
                                                Size: data.Size,
                                                BrandSKU: data.BrandSKU,
                                            },
                                            function () {
                                                linkKontrolCount = 0
                                                urunKontrolCount = 0
                                                var link1 = data.ProductURL
                                                // if(data.KontrolUrl1 == data.KontrolUrl2)
                                                // {
                                                // chrome.storage.sync.set({
                                                // "Durum": "FiyatKontrol"
                                                // },function () {
                                                // SiparisLinkleriGetir(data.ID, data.AmazonUrl, data.AbeUrl);
                                                // });

                                                // }else{link1

                                                SekmeAc(link1)

                                                //AmazonUrl = data.AmazonUrl;
                                                //AbeUrl = data.AbeUrl;
                                                console.log('Sekmeler Açılacak!')
                                                if (
                                                    host == 'www.amazon.com' ||
                                                    host == 'www.amazon.de' ||
                                                    host == 'www.amazon.fr' ||
                                                    host == 'www.amazon.co.uk' ||
                                                    host == 'www.abebooks.com' ||
                                                    host == 'www.wayfair.com' ||
                                                    host == 'www.wayfair.de' ||
                                                    host == 'www.wayfair.co.uk' ||
                                                    host == 'www.wayfair.ca' ||
                                                    host == 'www.overstock.com' ||
                                                    host == 'www.walmart.com' ||
                                                    host == 'www.homedepot.com' ||
                                                    host == 'www.markandday.com' ||
                                                    host == 'www.boutiquerugs.com' ||
                                                    host == 'www.rugs-direct.com'
                                                ) {
                                                    SekmeKapat(2)
                                                }
                                                //}
                                            }
                                        )
                                    } else {
                                        console.log('istenilen id ler değil')
                                        setTimeout(function () {
                                            UrunGetir()
                                        }, 1000)
                                    }
                                }
                            }
                            console.log('UrunGetir() Response!')
                        },
                        error: function (req, textStatus, errorThrown) {
                            console.log('Ooops, something happened: ' + textStatus + ' ' + errorThrown)
                            UrunGetir()
                        },
                    })
                }
            })
        }, 2000)
    }
}

var count = 0
function BirinciLinkKontrol(KontrolUrl2, Sorgu) {
    let URL = ''
    chrome.storage.sync.get(['Url'], function (item) {
        var host = window.location.host

        if (host == 'boutiquerugs.com') {
            if (document.querySelector('body').textContent.includes('404 Error - Page not found')) {
                chrome.storage.sync.set(
                    {
                        KontrolUrl1: 'Hardcover',
                        KontrolUrl2: 'Hardcover',
                        Titles: 'deneme',
                        Price: '',
                        Review: '',
                        Rating: '',
                        Stock: true,
                        brokenlink: 1,
                    },
                    function () {
                        //console.log("Birinci url kontrol edildi: " + deger);
                        console.log('Link is broken')
                        SekmeKapat(1)
                    }
                )
            } else {
                chrome.storage.sync.get(['Size'], function (item) {
                    $('div.ProductForm__Variants div.ProductForm__Option ul li label').each(function () {
                        if ($(this).text().replace(/\D/g, '') == item.Size) {
                            $(this).click()
                        }
                    })
                })
                setTimeout(function () {
                    let in_stock = true
                    if ($('#klaviyoInStockNotify').attr('style') === 'display: flex !important') in_stock = false

                    if (document.querySelector('span.price.price--withoutTax.color-red.price-custom-now'))
                        var fiyat = document.querySelector('span.price.price--withoutTax.color-red.price-custom-now').textContent.split('$')[1]
                    if (document.querySelector('#discounted-price')) var fiyat = document.querySelector('#discounted-price').textContent.split('$')[1]
                    if (
                        document.querySelector(
                            'div.productView > section:nth-child(1) > div > div.yotpo.bottomLine.yotpo-medium > div > div.standalone-bottomline > div.yotpo-bottomline.pull-left.star-clickable > a'
                        )
                    )
                        var review = document
                            .querySelector(
                                'div.productView > section:nth-child(1) > div > div.yotpo.bottomLine.yotpo-medium > div > div.standalone-bottomline > div.yotpo-bottomline.pull-left.star-clickable > a'
                            )
                            .textContent.split(' ')[0]
                    if (
                        document.querySelector(
                            'div.productView > section:nth-child(1) > div > div.yotpo.bottomLine.yotpo-medium > div > div.standalone-bottomline > div.yotpo-bottomline.pull-left.star-clickable > a'
                        )
                    )
                        var rating = document
                            .querySelector(
                                'div.productView > section:nth-child(1) > div > div.yotpo.bottomLine.yotpo-medium > div > div.standalone-bottomline > div.yotpo-bottomline.pull-left.star-clickable > a'
                            )
                            .getAttribute('aria-label')
                            .split(' ')[0]

                    chrome.storage.sync.set(
                        {
                            KontrolUrl1: 'Hardcover',
                            KontrolUrl2: 'Hardcover',
                            Titles: 'deneme',
                            Price: fiyat,
                            Review: review,
                            Rating: rating,
                            brokenlink: 0,
                            Stock: in_stock,
                        },
                        function () {
                            //console.log("Birinci url kontrol edildi: " + deger);
                            console.log('Fiyat:' + fiyat + ' Review:' + review + ' Rating:' + rating)
                            SekmeKapat(1)
                        }
                    )
                    HataKontrolYap(250)
                }, 6000)
            }
        }
        if (host == 'www.rugs-direct.com') {
            if (
                document.querySelector(
                    '#pdp-container > div.right-panel > div.buybox > div > div.product-form > div.drawer-buttons > div.btn-drawer.select-size'
                )
            )
                document
                    .querySelector(
                        '#pdp-container > div.right-panel > div.buybox > div > div.product-form > div.drawer-buttons > div.btn-drawer.select-size'
                    )
                    .click()

            let option = false
            chrome.storage.sync.get(['Size'], function (item) {
                $('#product_option_holder div.drawer_content div div.product_size span.sizedesc').each(function () {
                    if ($(this).text().replace(/\D/g, '') == item.Size.replace(/\D/g, '')) {
                        option = true
                        $(this).click()
                    }
                })
            })

            if (document.querySelector('.discontinued')) {
                chrome.storage.sync.set(
                    {
                        KontrolUrl1: 'Hardcover',
                        KontrolUrl2: 'Hardcover',
                        Titles: 'deneme',
                        Price: '',
                        Review: '',
                        Rating: '',
                        Stock: true,
                        brokenlink: 1,
                    },
                    function () {
                        //console.log("Birinci url kontrol edildi: " + deger);
                        console.log('Link is broken')
                        SekmeKapat(1)
                    }
                )
            } else {
                chrome.storage.sync.get(['BrandSKU'], function (item) {
                    console.log(item.BrandSKU)
                    $('#product_option_holder  div.drawer_content  div.product_tile').each(function () {
                        if ($(this).attr('data-itemno') == item.BrandSKU) {
                            $(this).click()
                        }
                    })
                })

                setTimeout(function () {
                    if (document.querySelector('#pdp-prod-info-container > div.prod_price'))
                        var fiyat = document.querySelector('#pdp-prod-info-container > div.prod_price').textContent.split('$')[1]
                    if (document.querySelector('div.price-range')) var fiyat = document.querySelector('div.price-range').textContent.split('$')[1]

                    if (
                        document.querySelector(
                            '#pdp-prod-name-container > div.prod_review > a > div > div > div.standalone-bottomline > div.yotpo-bottomline.pull-left.star-clickable > a'
                        )
                    )
                        var review = document
                            .querySelector(
                                '#pdp-prod-name-container > div.prod_review > a > div > div > div.standalone-bottomline > div.yotpo-bottomline.pull-left.star-clickable > a'
                            )
                            .textContent.split(' ')[0]

                    if (
                        document.querySelector(
                            '#pdp-prod-name-container > div.prod_review > a > div > div > div.standalone-bottomline > div.yotpo-bottomline.pull-left.star-clickable > span > span.sr-only'
                        )
                    )
                        var rating = document
                            .querySelector(
                                '#pdp-prod-name-container > div.prod_review > a > div > div > div.standalone-bottomline > div.yotpo-bottomline.pull-left.star-clickable > span > span.sr-only'
                            )
                            .textContent.split(' ')[0]

                    if (!option) fiyat = 0
                    chrome.storage.sync.set(
                        {
                            KontrolUrl1: 'Hardcover',
                            KontrolUrl2: 'Hardcover',
                            Titles: 'deneme',
                            Price: fiyat,
                            Review: review,
                            Rating: rating,
                            Stock: true,
                            brokenlink: 0,
                        },
                        function () {
                            console.log('Fiyat:' + fiyat + ' Review:' + review + ' Rating:' + rating)

                            SekmeKapat(1)
                        }
                    )
                    HataKontrolYap(250)
                }, 5000)
            }
        }
        if (host == 'markandday.com') {
            if (document.querySelector('body').textContent.includes('404 Page Not Found')) {
                chrome.storage.sync.set(
                    {
                        KontrolUrl1: 'Hardcover',
                        KontrolUrl2: 'Hardcover',
                        Titles: 'deneme',
                        Price: '',
                        Review: '',
                        Rating: '',
                        Stock: true,
                        brokenlink: 1,
                    },
                    function () {
                        //console.log("Birinci url kontrol edildi: " + deger);
                        console.log('Link is broken')
                        SekmeKapat(1)
                    }
                )
            } else {
                let in_stock = true
                if ($('#addbuttons:hidden').attr('id')) in_stock = false
                if ($('#addbuttons').attr('id') === undefined) in_stock = false

                if (document.querySelector('#ProductPrice')) var fiyat = document.querySelector('#ProductPrice').textContent.split('$')[1]

                if (document.querySelector('#currentvariantprice1'))
                    var fiyat = document.querySelector('#currentvariantprice1').textContent.split('$')[1]

                if (
                    document.querySelector(
                        '#ProductSection > div.product-single > div > div.grid__item.post-large--one-half.product_single-details > div > div.product-single__prices > div.yotpo.bottomLine.yotpo-medium > div > div.standalone-bottomline > div.yotpo-bottomline.pull-left.star-clickable > a'
                    )
                )
                    var review = document
                        .querySelector(
                            '#ProductSection > div.product-single > div > div.grid__item.post-large--one-half.product_single-details > div > div.product-single__prices > div.yotpo.bottomLine.yotpo-medium > div > div.standalone-bottomline > div.yotpo-bottomline.pull-left.star-clickable > a'
                        )
                        .textContent.split(' ')[0]

                if (
                    document.querySelector(
                        '#ProductSection > div.product-single > div > div.grid__item.post-large--one-half.product_single-details > div > div.product-single__prices > div.yotpo.bottomLine.yotpo-medium > div > div.standalone-bottomline > div.yotpo-bottomline.pull-left.star-clickable > a'
                    )
                )
                    var rating = document
                        .querySelector(
                            '#ProductSection > div.product-single > div > div.grid__item.post-large--one-half.product_single-details > div > div.product-single__prices > div.yotpo.bottomLine.yotpo-medium > div > div.standalone-bottomline > div.yotpo-bottomline.pull-left.star-clickable > a'
                        )
                        .getAttribute('aria-label')
                        .split(' ')[0]
                chrome.storage.sync.set(
                    {
                        KontrolUrl1: 'Hardcover',
                        KontrolUrl2: 'Hardcover',
                        Titles: 'deneme',
                        Price: fiyat,
                        Review: review,
                        Rating: rating,
                        Stock: in_stock,
                        brokenlink: 0,
                    },
                    function () {
                        console.log('Fiyat:' + fiyat + ' Review:' + review + ' Rating:' + rating)

                        SekmeKapat(1)
                    }
                )
                HataKontrolYap(250)
            }
        }
        if (host == 'www.homedepot.com') {
            if (document.querySelector('body').textContent.includes('The product you are trying to view is not currently available.')) {
                chrome.storage.sync.set(
                    {
                        KontrolUrl1: 'Hardcover',
                        KontrolUrl2: 'Hardcover',
                        Titles: 'deneme',
                        Price: '',
                        Review: '',
                        Rating: '',
                        Stock: true,
                        brokenlink: 1,
                    },
                    function () {
                        //console.log("Birinci url kontrol edildi: " + deger);
                        console.log('Link is broken')
                        SekmeKapat(1)
                    }
                )
            } else {
                var fiyat = null
                if (document.querySelector('#ajaxPrice > span.price__dollars'))
                    var dolar = document.querySelector('#ajaxPrice > span.price__dollars').textContent.trim()
                else if (document.querySelector('div.price > div.price-format__large.price-format__main-price > span:nth-child(2)'))
                    dolar = document
                        .querySelector('div.price > div.price-format__large.price-format__main-price > span:nth-child(2)')
                        .textContent.trim()
                else if (document.querySelector('#standard-price > div > div > span:nth-child(2)'))
                    dolar = document.querySelector('#standard-price > div > div > span:nth-child(2)').textContent.trim()
                if (document.querySelector('#ajaxPrice > span.price__cents'))
                    var cent = document.querySelector('#ajaxPrice > span.price__cents').textContent
                if (document.querySelector('#was-price > div.price > div.price-format__large.price-format__main-price > span:nth-child(3)'))
                    cent = document.querySelector(
                        '#was-price > div.price > div.price-format__large.price-format__main-price > span:nth-child(3)'
                    ).textContent
                if (document.querySelector('#standard-price > div > div > span:nth-child(3)'))
                    cent = document.querySelector('#standard-price > div > div > span:nth-child(3)').textContent

                if (dolar != '' && cent != '' && dolar != undefined && cent != undefined) var fiyat = dolar + '.' + cent

                if (document.querySelector('#BVRRSummaryContainer  span.product-details__review-count'))
                    var review = document
                        .querySelector('#BVRRSummaryContainer  span.product-details__review-count')
                        .textContent.split('(')[1]
                        .split(')')[0]
                if (document.querySelector('#product-details__review__target > span.product-details__review-count'))
                    review = document
                        .querySelector('#product-details__review__target > span.product-details__review-count')
                        .textContent.split('(')[1]
                        .split(')')[0]
                if (document.querySelector('#BVRRSummaryContainer > div > div:nth-child(2) > a > span > div > span'))
                    var rating = document
                        .querySelector('#BVRRSummaryContainer > div > div:nth-child(2) > a > span > div > span')
                        .parentElement.getAttribute('title')
                        .split(' ')[0]
                if (document.querySelector('div.loader__content > a'))
                    var rating = document.querySelector(' div.loader__content > a').getAttribute('title').split(' ')[0]

                if (fiyat === undefined) fiyat = null
                if (review === undefined) review = null
                if (rating === undefined) rating = null

                chrome.storage.sync.set(
                    {
                        KontrolUrl1: 'Hardcover',
                        KontrolUrl2: 'Hardcover',
                        Titles: 'deneme',
                        Price: fiyat,
                        Review: review,
                        Rating: rating,
                        Stock: true,
                        brokenlink: 0,
                    },
                    function () {
                        //console.log("Birinci url kontrol edildi: " + deger);
                        console.log('Fiyat:' + fiyat + ' Review:' + review + ' Rating:' + rating)
                        SekmeKapat(1)
                    }
                )
                HataKontrolYap(250)
            }
        }
        if (host == 'www.overstock.com') {
            if (document.getElementsByTagName('title')[0].innerHTML === '406 Not Acceptable') {
                UrunKilitAc()
            } else {
                if (document.querySelector('body').textContent.includes('We’re Sorry')) {
                    chrome.storage.sync.set(
                        {
                            KontrolUrl1: 'Hardcover',
                            KontrolUrl2: 'Hardcover',
                            Titles: 'deneme',
                            Price: '',
                            Review: '',
                            Rating: '',
                            Stock: true,
                            brokenlink: 1,
                        },
                        function () {
                            //console.log("Birinci url kontrol edildi: " + deger);
                            console.log('Link is broken')
                            SekmeKapat(1)
                        }
                    )
                } else {
                    let in_stock = true
                    // if (document.querySelector("#top-refinements > article > div > div > div._3VLphu > div.os-alert-cl-wrapper.error.lg"))
                    //     in_stock = false;

                    if (document.querySelector('#product-price')) var fiyat = document.querySelector('#product-price').textContent.split('$')[1]
                    if (document.querySelector('#product-price-price-container'))
                        var fiyat = document.querySelector('#product-price-price-container').textContent.split('$')[1]
                    if (document.querySelector('div[data-testid=current-price]'))
                        var fiyat = document.querySelector('div[data-testid=current-price]').textContent.split('$')[1].split('Tag')[0]
                    if (document.querySelector('section > div:nth-child(2) > section > a'))
                        var review = document.querySelector('section > div:nth-child(2) > section > a').textContent.split(' ')[0]
                    if ($('section[data-cy=price-set-reviews-rating]'))
                        var review = $('section[data-cy=price-set-reviews-rating]').text().trim().split(' ')[0]
                    if (document.querySelector("#__next span[data-testid='reviews-count']").length)
                        var review = document.querySelector("#__next span[data-testid='reviews-count']").textContent
                    if ($('section[data-cy=price-set-reviews-rating]').find('.os-cl-rating').attr('title'))
                        var rating = $('section[data-cy=price-set-reviews-rating]')
                            .find('.os-cl-rating')
                            .attr('title')
                            .split('Review Average')[1]
                            .trim()

                    if (document.querySelector('#_1v8PXey > section > div:nth-child(2) > section > a > div > div')) {
                        var per = document
                            .querySelector('#_1v8PXey > section > div:nth-child(2) > section > a > div > div > div > div.front')
                            .getAttribute('style')
                            .split('width:')[1]
                            .split('%')[0]
                        var rating = (5 * per) / 100
                    } else if (
                        document.querySelector(
                            '#mainContent > section.content-section.cf > div > div.col-xs-6.add-to-cart-container > div.row.ratings-container > div.ratings-size > div > a > div.rating-star-container.add-to-cart-rating-stars'
                        )
                    ) {
                        var rating = document
                            .querySelector(
                                '#mainContent > section.content-section.cf > div > div.col-xs-6.add-to-cart-container > div.row.ratings-container > div.ratings-size > div > a > div.rating-star-container.add-to-cart-rating-stars'
                            )
                            .getAttribute('data-rating')
                    }
                    if ($('#__next  div.cl-rating').length) var rating = $('#__next  div.cl-rating').attr('title').split('Review Average')[1].trim()

                    console.log('Fiyat:' + fiyat + ' Review:' + review + ' Rating:' + rating)

                    chrome.storage.sync.set(
                        {
                            KontrolUrl1: 'Hardcover',
                            KontrolUrl2: 'Hardcover',
                            Titles: 'deneme',
                            Price: fiyat,
                            Review: review,
                            Rating: rating,
                            brokenlink: 0,
                            Stock: in_stock,
                        },
                        function () {
                            //console.log("Birinci url kontrol edildi: " + deger);
                            console.log('Fiyat:' + fiyat + ' Review:' + review + ' Rating:' + rating)
                            SekmeKapat(1)
                        }
                    )
                    HataKontrolYap(250)
                }
            }
        }
        if (host == 'www.wayfair.com' || host == 'www.wayfair.de' || host == 'www.wayfair.co.uk' || host == 'www.wayfair.ca') {
            console.log(window.location.href)
            console.log(item.Url)

            if (window.location.pathname === '/v/captcha/show') {
                UrunKilitAc()
            } else {
                // if ((window.location.href !== item.Url) && (document.querySelector("#sf-ui-product-details\\:\\:application") === null)) {
                //     chrome.storage.sync.set({
                //         'KontrolUrl1': 'Hardcover',
                //         'KontrolUrl2': 'Hardcover',
                //         'Titles': 'deneme',
                //         'Price': "",
                //         'Review': "",
                //         'Rating': "",
                //         'Stock' : true,
                //         'brokenlink': 1
                //     }, function () {
                //         //console.log("Birinci url kontrol edildi: " + deger);
                //         console.log("Link is broken");
                //         SekmeKapat(1);
                //     });
                // }
                // else {
                let currency = '$'
                let arrayIndex = 1
                if (host == 'www.wayfair.de') {
                    currency = '€'
                    arrayIndex = 0
                }

                if (host == 'www.wayfair.co.uk') {
                    currency = '£'
                    arrayIndex = 1
                }

                if (document.querySelector('div.BasePriceBlock > span'))
                    var fiyat = document.querySelector('div.BasePriceBlock > span').textContent.split(currency)[arrayIndex].trim()
                if (document.querySelector('span.pl-Price-V2.pl-Price-V2--5000'))
                    var fiyat = document.querySelector('span.pl-Price-V2.pl-Price-V2--5000').textContent.split(currency)[arrayIndex].trim()
                if (document.querySelector('span.ProductRatingNumberWithCount-count'))
                    var review = document.querySelector('span.ProductRatingNumberWithCount-count').textContent.split(' ')[0]
                if (document.querySelector('span.ProductRatingNumberWithCount-rating'))
                    var rating = document.querySelector('span.ProductRatingNumberWithCount-rating').textContent

                let in_stock = true
                if (
                    document.querySelector(
                        '#bd > div.pl-Wrapper > div.PdpLayoutResponsive-top > div > div.pl-Box--display-flex.pl-Box--pb-8-bp960.pl-Box--pt-8-bp960.pl-Box--pr-6-bp960.pl-Box--fd-column.pl-Box--fw-wrap.pl-Box--size-12.pl-Box--size-6-bp960.pl-Grid-item.pl-Box--defaultColor > div.PdpLayoutResponsive-stickyWrap > div > div > div > div.ProductDetailImageCarousel-top > div.ProductDetailImageCarousel-container > div > button'
                    )
                )
                    in_stock = false

                console.log('Fiyat:' + fiyat + ' Review:' + review + ' Rating:' + rating)
                chrome.storage.sync.set(
                    {
                        KontrolUrl1: 'Hardcover',
                        KontrolUrl2: 'Hardcover',
                        Titles: 'deneme',
                        Price: fiyat,
                        Review: review,
                        Rating: rating,
                        brokenlink: 0,
                        Stock: in_stock,
                    },
                    function () {
                        //console.log("Birinci url kontrol edildi: " + deger);
                        //console.log("Fiyat:" + fiyat + " Review:" + review + " Rating:" + rating);
                        SekmeKapat(1)
                    }
                )
                HataKontrolYap(250)
            }
            //}
        }
        if (host == 'www.walmart.com') {
            if (window.location.pathname === '/blocked') {
                UrunKilitAc()
            } else {
                if (document.querySelector('span.w_B3.w_B4.mb6.tc')) {
                    chrome.storage.sync.set(
                        {
                            KontrolUrl1: 'Hardcover',
                            KontrolUrl2: 'Hardcover',
                            Titles: 'deneme',
                            Price: '',
                            Review: '',
                            Rating: '',
                            Stock: true,
                            brokenlink: '1',
                        },
                        function () {
                            //console.log("Birinci url kontrol edildi: " + deger);
                            console.log('Link is broken')
                            SekmeKapat(1)
                        }
                    )
                } else {
                    let in_stock = true
                    if (
                        document.querySelector(
                            '#__next > div:nth-child(1) > div > div > div.flex-auto.relative.z-1 > div > section > main > div > div:nth-child(2) > div > div.w_CM.w_DL.w_CQ > div > div > div.slide-sticky-buy-box-up.z-5 > div > div > div.pt3.f4.light-gray > div > div > div.b.gray.lh-copy.pt2-m.flex.fr-m.\\"f4.tr'
                        )
                    )
                        in_stock = false

                    if (
                        document.querySelector(
                            '#price > div > span.hide-content.display-inline-block-m > span > span.price-group > span.price-characteristic'
                        )
                    )
                        var fiyat = document
                            .querySelector(
                                '#price > div > span.hide-content.display-inline-block-m > span > span.price-group > span.price-characteristic'
                            )
                            .getAttribute('content')
                    if (document.querySelector('span[itemprop=price]'))
                        var fiyat = document.querySelector('span[itemprop=price]').textContent.split('$')[1]
                    if (
                        document.querySelector(
                            'div.prod-productsecondaryinformation.display-inline-block.prod-SecondaryInfo > div.secondary-info-margin-right.secondary-margin-bottom.display-inline-block.valign-middle > div > span.stars-reviews.font-normal > span'
                        )
                    )
                        var review = document
                            .querySelector(
                                'div.prod-productsecondaryinformation.display-inline-block.prod-SecondaryInfo > div.secondary-info-margin-right.secondary-margin-bottom.display-inline-block.valign-middle > div > span.stars-reviews.font-normal > span'
                            )
                            .textContent.split(' ')[0]
                    if (
                        document.querySelector(
                            'body > div.js-content > div.page-wrapper > div > div.js-body-content > div > div.atf-content > div > div:nth-child(1) > div > div > div > div > div.Grid > div.product-atf > div > div:nth-child(3) > div > div.prod-productsecondaryinformation.display-inline-block.prod-SecondaryInfo > div.secondary-info-margin-right.secondary-margin-bottom.display-inline-block.valign-middle > div > span.stars-container'
                        )
                    )
                        var rating = document
                            .querySelector(
                                'body > div.js-content > div.page-wrapper > div > div.js-body-content > div > div.atf-content > div > div:nth-child(1) > div > div > div > div > div.Grid > div.product-atf > div > div:nth-child(3) > div > div.prod-productsecondaryinformation.display-inline-block.prod-SecondaryInfo > div.secondary-info-margin-right.secondary-margin-bottom.display-inline-block.valign-middle > div > span.stars-container'
                            )
                            .getAttribute('aria-label')
                            .split(' ')[0]
                    chrome.storage.sync.set(
                        {
                            KontrolUrl1: 'Hardcover',
                            KontrolUrl2: 'Hardcover',
                            Titles: 'deneme',
                            Price: fiyat,
                            Review: review,
                            Rating: rating,
                            brokenlink: '0',
                            Stock: in_stock,
                        },
                        function () {
                            //console.log("Birinci url kontrol edildi: " + deger);
                            console.log('Fiyat:' + fiyat + ' Review:' + review + ' Rating:' + rating)
                            SekmeKapat(1)
                        }
                    )
                    HataKontrolYap(250)
                }
            }
        }
        if (host == 'www.amazon.com' || host == 'www.amazon.de' || host == 'www.amazon.co.uk' || host == 'www.amazon.fr') {
            var rank = ''
            var aramaTextBox = $('#twotabsearchtextbox')
            var myElem = document.querySelector('title')
            if (document.querySelector('#glow-ingress-line2').textContent.trim() == 'Select your address') {
                document.querySelector('#nav-global-location-popover-link').click()
                setTimeout(function () {
                    document.querySelector('#GLUXZipUpdateInput').value = '90001'
                    document.querySelector('#GLUXZipUpdate > span > input').click()
                    document.querySelector('#a-popover-1 > div > div.a-popover-footer > span > span > span > button').click()
                }, 1000)
            }

            setTimeout(function () {
                if (myElem != null) {
                    if (myElem.textContent.trim() == 'Page Not Found') {
                        chrome.storage.sync.set(
                            {
                                KontrolUrl1: 'Hardcover',
                                KontrolUrl2: 'Hardcover',
                                Titles: 'deneme',
                                Price: '',
                                Review: '',
                                Rating: '',
                                Stock: true,
                                brokenlink: 1,
                            },
                            function () {
                                //console.log("Birinci url kontrol edildi: " + deger);
                                console.log('Fiyat:' + fiyat + ' Review:' + review + ' Rating:' + rating)
                                SekmeKapat(1)
                            }
                        )
                    } else if (aramaTextBox.length) {
                        if ($('#productDetails_detailBullets_sections1')) {
                            $('#productDetails_detailBullets_sections1 > tbody > tr > th').each(function () {
                                if ($(this).text().trim() == 'Best Sellers Rank') {
                                    var categoryName = $('#wayfinding-breadcrumbs_feature_div > ul > li:last-child > span > a').text().trim()
                                    var rankTemp = $(this).parent().find('span').find('span').text().trim()
                                    var r = $(this).next().find('span').last().text().trim()
                                    rank = r.split(' ')[0].split('#')[1]
                                    console.log(r.split(' ')[0].split('#')[1])
                                }
                            })
                        }

                        let currency = '$'
                        let arrayIndex = 1
                        if (host == 'www.amazon.de') {
                            currency = '€'
                            arrayIndex = 0
                        }

                        if (host == 'www.amazon.co.uk') {
                            currency = '£'
                            arrayIndex = 1
                        }

                        let in_stock = true
                        // if(document.querySelector("#availability > span").textContent.trim() == 'Currently unavailable.')
                        //     in_stock = false;

                        if (document.querySelector('#priceblock_ourprice'))
                            var fiyat = document.querySelector('#priceblock_ourprice').textContent.trim().split(currency)[arrayIndex]
                        if (document.querySelector('#priceblock_dealprice'))
                            var fiyat = document.querySelector('#priceblock_dealprice').textContent.trim().split(currency)[arrayIndex]
                        if (document.querySelector('#corePrice_desktop span.a-price.a-text-price.a-size-medium.apexPriceToPay  span:nth-child(2)'))
                            var fiyat = document
                                .querySelector('#corePrice_desktop span.a-price.a-text-price.a-size-medium.apexPriceToPay  span:nth-child(2)')
                                .textContent.trim()
                                .split(currency)[arrayIndex]
                        if (
                            document.querySelector(
                                '#corePriceDisplay_desktop_feature_div > div.a-section.a-spacing-none.aok-align-center > span.a-price.aok-align-center.priceToPay > span.a-offscreen'
                            )
                        )
                            var fiyat = document
                                .querySelector(
                                    '#corePriceDisplay_desktop_feature_div > div.a-section.a-spacing-none.aok-align-center > span.a-price.aok-align-center.priceToPay > span.a-offscreen'
                                )
                                .textContent.trim()
                                .split(currency)[arrayIndex]
                        if (document.querySelector('#acrCustomerReviewText'))
                            var review = document.querySelector('#acrCustomerReviewText').textContent.split(' ')[0]
                        if (document.querySelector('#acrPopover > span.a-declarative > a > i > span'))
                            var rating = document.querySelector('#acrPopover > span.a-declarative > a > i > span').textContent.split(' ')[0]
                        chrome.storage.sync.set(
                            {
                                KontrolUrl1: 'Hardcover',
                                KontrolUrl2: 'Hardcover',
                                Titles: 'deneme',
                                Price: fiyat,
                                Review: review,
                                Rating: rating,
                                brokenlink: 0,
                                Stock: in_stock,
                                rank: rank,
                            },
                            function () {
                                //console.log("Birinci url kontrol edildi: " + deger);
                                console.log('Fiyat:' + fiyat + ' Review:' + review + ' Rating:' + rating)
                                SekmeKapat(1)
                            }
                        )
                    } else {
                        console.log('Yenile')
                        UrunKilitAc()
                    }
                } else {
                    console.log('Yenile')
                    UrunKilitAc()
                }
            }, 2000)
        }
    })
}

function UrlKontrolYap() {
    var host = window.location.host
    if (host != 'www.amazon.com' && host != 'www.abebooks.com') {
        chrome.storage.sync.get(['KontrolUrl1', 'KontrolUrl2', 'UrunID', 'AbeUrl', 'AmazonUrl'], function (item) {
            console.log(item.KontrolUrl1 + ' ' + item.KontrolUrl2)
            linkKontrolCount = 0
            var id = item.UrunID
            AbeUrl = item.AbeUrl
            AmazonUrl = item.AmazonUrl

            if (item.KontrolUrl1 == item.KontrolUrl2) {
                console.log('doğru')
                //WHataliUrun(id);
                SiparisLinkleriGetir(id, AmazonUrl, AbeUrl)
            } else {
                if (
                    (item.KontrolUrl1 == 'Board book' || item.KontrolUrl1 == 'Hardcover') &&
                    (item.KontrolUrl2 == 'Board book' || item.KontrolUrl2 == 'Hardcover')
                ) {
                    console.log('deneme dogrusu')
                    //WHataliUrun(id);
                    SiparisLinkleriGetir(id, AmazonUrl, AbeUrl)
                } else {
                    console.log('yanlış')
                    HataliUrun(id)
                    //SiparisLinkleriGetir(id, AmazonUrl, AbeUrl);
                }
            }
        })
    }
}
function UrunKilitAc() {
    chrome.storage.sync.get(['UrunID'], function (item) {
        console.log('Hatalı Ürün bildirilecek!')
        $.ajax({
            type: 'get',
            url: 'https://www.ecompricetracking.com/api/resetLock/' + item.UrunID,
            beforeSend: function (xhr) {
                xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
            },
            cache: false,
        })
        UrunGetir()
        console.log(item.UrunID + " Nolu id'ye sahip ürün hatali")
    })
}

function HataliUrun(id) {
    console.log('Hatalı Ürün bildirilecek!')
    $.ajax({
        type: 'post',
        url: 'https://www.andromedaworkspace.com/Extension/ajaxCall',
        beforeSend: function (xhr) {
            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
        },
        cache: false,
        dataType: 'json',
        data: {
            ID: id,
            tip: 'newOrderStartFalse',
        },
        success: function (cevap) {
            if (cevap.hata) {
                console.log('Hata')
            } else {
                if (cevap.result) {
                    console.log(cevap.result)
                    linkKontrolCount = 0
                    urunKontrolCount = 0
                    UrunGetir()
                }
            }
        },
        error: function (req, textStatus, errorThrown) {
            console.log('Ooops, something happened: ' + textStatus + ' ' + errorThrown)
        },
    })
    console.log(id + " Nolu id'ye sahip ürün hatali")
}

function SiparisLinkleriGetir(id, AmazonUrl, AbeUrl) {
    chrome.storage.sync.set(
        {
            Durum: 'FiyatKontrol',
            KontrolUrl1: '',
            KontrolUrl2: '',
            AmzPageCount: 0,
            AbePageCount: 0,
        },
        function () {
            var amazonLink = AmazonUrl + '&PgNm=Amz'
            var abeLink = AbeUrl + '&PgNm=Abe'
            chrome.storage.local.set(
                {
                    AbeUrl: AbeUrl,
                    AmazonUrl: AmazonUrl,
                    AbeUrunList: null,
                    AmzUrunList: null,
                    SiparisBilgileri: null,
                },
                function () {
                    linkKontrolCount = 0
                    urunKontrolCount = 0
                    console.log('amazonlink-->' + amazonLink)
                    console.log('abelink-->' + abeLink)
                    SekmeAc(amazonLink)
                    SekmeAc(abeLink)
                    console.log('Amazon ve Abebook Ürün Sayfaları  Açılacak !')
                }
            )
        }
    )
}

var AbeUrunList = []

function AbeFiyatKontrol(fiyat, AbePageCount, AbeUrl) {
    console.log(AbeFiyatKontrol)
    var UrunList = localStorage.getItem('LSAbeUrunList')
    console.log(UrunList)
    if (UrunList != undefined) {
        AbeUrunList = JSON.parse(UrunList)
    }
    $('.highlighted-inventory').remove()
    var liste = $('.result-set').find('div.result')
    var listeItemCount = parseInt($('.result-set').find('div.result').length) - 1
    var FiyatKontrolTamamlandi = true
    liste.each(function (index) {
        //  var UrunFiyat = $(this).find(".item-price").find("span.price").text().split(" ")[1];
        //  var KargoFiyat = $(this).find(".shipping").find("span.price").text().split(" ")[1];
        try {
            var UrunFiyat = $(this).find('.srp-item-price').text().split(' ')[1].replace(',', '')
        } catch {
            var UrunFiyat = $(this).find('.srp-item-price').text().split(' ')[1]
        }
        var KargoFiyat = $(this).find('.srp-item-price-shipping').text().split(' ')[1]
        var DFiyat = parseFloat(fiyat)
        var DUrunFiyat = parseFloat(UrunFiyat)
        var DKargoFiyat = KargoFiyat != undefined ? parseFloat(KargoFiyat.replace(',', '')) : 0
        var Price = DUrunFiyat + DKargoFiyat
        if (DFiyat > Price) {
            var isAvailable = $(this).find('.bookseller-info').next('div').attr('class')
            console.log(isAvailable)
            if (isAvailable == 'print-on-demand' || isAvailable == 'international-edition') {
                console.log('eklenmeyecek')
            } else {
                var c = $(this).find('.clear-all').children().eq(1).text().split('Condition:')[1]
                var Condition = c != undefined ? c.split('.')[0].trim() : '-'
                var Seller = $(this).find('.bookseller-info').children().eq(0).children().text().trim()
                var Ratings = $(this).find('.bookseller-rating').children().eq(1).children('img').attr('alt').split('-')[0]
                // var Within = $(this).find(".shipping").next("div.small").text().trim();
                var Within = $(this).find('.srp-item-shipping-dest').text().trim()
                // var SellerHref = $(this).find(".shipping").next().next().children().eq(0).attr('href');
                var SellerHref = $(this).find('.srp-item-buybox ').children().last().children().last().attr('href')
                var SellerID = SellerHref.split(/[=&]/)[2]
                var ShippingDate = []
                var SellerLink = 'https://www.abebooks.com/servlet/ShipRates?vid=' + SellerID
                var gelenData = getSayfa(SellerLink)
                var parser = new DOMParser()
                var htmlDoc = parser.parseFromString(gelenData, 'text/html')
                var normal = $(htmlDoc).find('tbody > tr').eq(0).find('td').eq(1).text()

                ShippingDate = normal
                Price = Price.toFixed(2)
                var item = {
                    index,
                    Condition,
                    Seller,
                    Ratings,
                    Within,
                    ShippingDate,
                    Price,
                    Page: AbePageCount,
                }
                AbeUrunList.push(item)
            }

            console.log('listeItemCount: ' + listeItemCount)
            console.log('index: ' + index)
            if (listeItemCount == index && listeItemCount != 0) {
                FiyatKontrolTamamlandi = true
                localStorage.setItem('LSAbeUrunList', JSON.stringify(AbeUrunList))
            } else {
                FiyatKontrolTamamlandi = true
            }
        } else {
        }
    })

    console.log('FiyatKontrolTamamlandi: ' + FiyatKontrolTamamlandi)
    if (FiyatKontrolTamamlandi) {
        console.log('Verileri Gonder')
        console.table(AbeUrunList)
        var isbn = QueryStringOku('isbn')
        chrome.storage.local.set(
            {
                AbeUrunList: AbeUrunList,
                ISBN: isbn,
                UrunFiyat: fiyat,
            },
            function () {
                console.log('AbeUrunList kontrol edildi: ')
                localStorage.removeItem('LSAbeUrunList')
                SekmeKapat(1)
            }
        )
    } else {
        var PaginationNext = parseInt(AbePageCount) + 1
        chrome.storage.sync.set(
            {
                AbePageCount: PaginationNext,
            },
            function () {
                //https://www.abebooks.com/servlet/SearchResults?isbn=0452266556&n=100121501&sortby=17&cm_sp=pan-_-srp-_-new
                var abelink = AbeUrl
                var PaginationNextCount = PaginationNext * 30
                var params = `?PgNm=Abe&bsi=${PaginationNextCount}`
                var link = abelink + params
                console.log('diğer sayfaya gec')
                SayfaGit(link, 1)
            }
        )
    }
}

var AmzUrunList = []

function AmazonFiyatKontrol(fiyat, AmzPageCount, AmazonUrl) {
    var UrunList = localStorage.getItem('LSAmazonUrunList')
    if (UrunList != undefined) {
        AmzUrunList = JSON.parse(UrunList)
    }
    var liste = $('#olpOfferList').find('.olpOffer')
    var listeItemCount = parseInt($('#olpOfferList').find('.olpOffer').length) - 1
    var FiyatKontrolTamamlandi = true
    liste.each(function (index) {
        // $(this).find(".olpFastTrack").find("a").parent().remove("").end();
        var UrunFiyat = $(this).find('.olpOfferPrice').text().trim().substr(1).replace(',', '')
        var KargoFiyat = $(this).find('.olpShippingPrice').text().trim().substr(1)
        var DFiyat = parseFloat(fiyat)
        var DUrunFiyat = parseFloat(UrunFiyat)
        var DKargoFiyat = KargoFiyat.length > 0 ? parseFloat(KargoFiyat.replace(',', '')) : 0
        var Price = DUrunFiyat + DKargoFiyat
        if (DFiyat > Price) {
            var Condition = $(this)
                .find('.olpCondition')
                .text()
                .split('\n')
                .map((item) => item.trim())
                .join(' ')
                .trim()
            var Delivery = $(this)
                .find('.olpFastTrack')
                .text()
                .split('\n')
                .map((item) => item.trim())
                .join(' ')
                .trim()
            var isPrime = $(this).find('.olpPriceColumn').find('span.supersaver').length > 0 ? true : false
            var Seller = $(this).find('.olpSellerName').text().trim()
            var Positive = $(this).find('.olpSellerColumn').children('p').children().eq(1).text().split('%')[0]
            var r = $(this).find('.olpSellerColumn').children('p').clone().children().remove().end().text().trim().split(/[()]/)[1]
            var Ratings = r != undefined ? r.split(' ')[0] : '-'
            Price = Price.toFixed(2)
            if (isPrime) {
                Seller = 'Amazon.com'
            }
            var item = {
                index,
                isPrime,
                Condition,
                Delivery,
                Seller,
                Positive,
                Ratings,
                Price,
                Page: AmzPageCount,
            }
            AmzUrunList.push(item)
            console.log(listeItemCount + ' ' + index + ' ' + listeItemCount)
            if (listeItemCount == index && listeItemCount != 0) {
                FiyatKontrolTamamlandi = true
                localStorage.setItem('LSAmazonUrunList', JSON.stringify(AmzUrunList))
            } else {
                FiyatKontrolTamamlandi = true
            }
        } else {
            console.log('Fiyat Yüksek')
        }
    })
    console.log(AmzUrunList)
    if (FiyatKontrolTamamlandi) {
        console.log('Verileri Gonder')
        console.table(AmzUrunList)
        chrome.storage.local.set(
            {
                AmzUrunList: AmzUrunList,
                AmazonUrl: AmazonUrl,
                UrunFiyat: fiyat,
            },
            function () {
                console.log('AmzUrunList kontrol edildi: ')
                localStorage.removeItem('LSAmazonUrunList')
                SekmeKapat(1)
            }
        )
    } else {
        console.log(AmzPageCount)
        var PaginationNext = parseInt(AmzPageCount) + 1
        chrome.storage.sync.set(
            {
                AmzPageCount: PaginationNext,
            },
            function () {
                var amzlink = AmazonUrl
                var params = '&PgNm=Amz&startIndex=' + PaginationNext * 10
                var link = amzlink + params
                console.log('diğer sayfaya gec')
                //SayfaGit(link, 1);
            }
        )
    }
}

function UrunZararYaz() {
    chrome.storage.sync.get(['UrunID'], function (item) {
        console.log('İstenilen ürüne  uygun fiyat ve diğer şartlar sağlanamadı!')
        var stringArray = []
        $.ajax({
            type: 'post',
            url: 'https://www.andromedaworkspace.com/Extension/ajaxCall',
            beforeSend: function (xhr) {
                xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
            },
            cache: false,
            dataType: 'json',
            data: {
                ID: item.UrunID,
                orderArray: stringArray,
                tip: 'newOrderFiltre',
            },
            success: function (cevap) {
                if (cevap.hata) {
                    console.log('Hata')
                } else {
                    if (cevap.result == null) {
                        console.log(cevap.result)
                        console.log('UrunZararYaz()  çalıştı!')
                        UrunGetir()
                    }
                }
            },
            error: function (req, textStatus, errorThrown) {
                console.log('Ooops, something happened: ' + textStatus + ' ' + errorThrown)
            },
        })
    })
}

function UrunAl(tekrar) {
    //siparisIndex, ItemIndex
    var host = 'window.location.host'
    chrome.storage.local.get(['SiparisBilgileri', 'UrunFiyat', 'SiparisListesiLastIndex', 'SiparisIndex', 'AmazonUrl', 'ISBN'], function (item) {
        var link = ''
        var isbn = item.ISBN
        var SiparisBilgileri = item.SiparisBilgileri
        var SiparisIndex = item.SiparisIndex
        var SiparisListesiLastIndex = item.SiparisListesiLastIndex
        console.log(SiparisListesiLastIndex)
        console.log(SiparisIndex)

        if (SiparisIndex < SiparisListesiLastIndex || SiparisIndex == SiparisListesiLastIndex) {
            var isMagazaAmazon = SiparisBilgileri[SiparisIndex]['Magaza'] == '0' ? true : false
            var Page = parseInt(SiparisBilgileri[SiparisIndex]['Page'])
            var Item = SiparisBilgileri[item.SiparisIndex]['Index']
            var NPrice = SiparisBilgileri[item.SiparisIndex]['SecondPrice']

            console.log('Nprice type: ' + typeof NPrice)

            if (NPrice == null) {
                NPrice = item.UrunFiyat
            }
            // if (isMagazaAmazon) {
            if (isMagazaAmazon) {
                console.log('Amazon Açılacak!')
                var SiparisIndexNext = parseInt(SiparisIndex) + 1 - tekrar
                chrome.storage.local.set(
                    {
                        SiparisIndex: SiparisIndexNext,
                    },
                    function () {
                        var amzlink = item.AmazonUrl
                        var amzparams = `&PgNm=Amz&startIndex=${Page * 10}&itemIndex=${Item}&itemPage=${Page}&NPrice=${NPrice}`
                        link = amzlink + amzparams
                        SekmeAc(link)
                    }
                )
            } else {
                console.log('Abebook Açılacak')
                var SiparisIndexNext = parseInt(SiparisIndex) + 1
                chrome.storage.local.set(
                    {
                        SiparisIndex: SiparisIndexNext,
                    },
                    function () {
                        if (item.AbeUrl == undefined) {
                            var abelink = AbeUrl
                        } else {
                            var abelink = item.AbeUrl
                        }

                        var abeparams = `&PgNm=Abe&bsi=${Page * 30}&itemIndex=${Item}&itemPage=${Page}&NPrice=${NPrice}`
                        link = abelink + abeparams
                        SekmeAc(link)
                    }
                )
            }
            if (host == 'www.amazon.com' || host == 'www.abebooks.com') {
                SekmeKapat(1)
            }
        } else {
            console.log('Sipariş Listesinde Uygun Sipariş Kalmadı!')
            UrunZararYaz()
        }
    })
}

function AmzUrunAl(IstenilenFiyat) {
    chrome.storage.local.get(['AmzUrunList'], function (item) {
        console.log(item.AmzUrunList)
        console.log('Amazon')
        var AmzUrunList = item.AmzUrunList
        var itemIndex = QueryStringOku('itemIndex')
        var itemPage = QueryStringOku('itemPage')
        var NPrice = QueryStringOku('NPrice')

        var LocaldekiUrun = AmzUrunList.find((item) => item.index == itemIndex && item.Page == itemPage)

        var Urun = $('#olpOfferList').find('.olpOffer').eq(itemIndex)
        var UrunFiyat = Urun.find('.olpOfferPrice').text().trim().substr(1)
        var KargoFiyat = Urun.find('.olpShippingPrice').text().trim().substr(1)
        var DUrunFiyat = parseFloat(UrunFiyat)
        var DKargoFiyat = KargoFiyat.length > 0 ? parseFloat(KargoFiyat) : 0
        var Price = DUrunFiyat + DKargoFiyat

        var Condition = Urun.find('.olpCondition')
            .text()
            .split('\n')
            .map((item) => item.trim())
            .join(' ')
            .trim()
        var Seller = Urun.find('.olpSellerName').text().trim()
        var r = Urun.find('.olpSellerColumn').children('p').clone().children().remove().end().text().trim().split(/[()]/)[1]
        var isPrime = Urun.find('.olpPriceColumn').find('span.supersaver').length > 0 ? true : false
        Price = Price.toFixed(2)
        var AmzSeller = LocaldekiUrun.Seller
        if (isPrime) {
            Seller = 'Amazon.com'
        }
        console.log('Localdeki:' + LocaldekiUrun.Condition + ' ' + LocaldekiUrun.Seller + ' ' + LocaldekiUrun.Price)
        console.log('Sayfadaki:' + Condition + ' ' + Seller + ' ' + Price)

        if (NPrice == null) {
            NPrice = IstenilenFiyat
        }
        if (
            (LocaldekiUrun.Condition == Condition && LocaldekiUrun.Seller == Seller && Price <= parseFloat(LocaldekiUrun.Price).toFixed(2)) ||
            parseFloat(Price).toFixed(2) <= parseFloat(NPrice).toFixed(2)
        ) {
            console.log('İki ürün aynı. İşlemler devam edecek (Amazon)')

            var link = window.location.href
            chrome.storage.sync.set(
                {
                    AmzSepetUrunLink: link,
                    AmzSeller: AmzSeller,
                    NextPrice: NPrice,
                },
                function () {
                    Urun.find('.a-button-input').click()
                    Urun.find('.a-button-input').trigger('click')
                }
            )
        } else {
            console.log('İki ürün aynı değil listedeki diğer ürüne geçilecek! (Amazon)')
            UrunAl(0)
        }
    })
}

var zarar = 0
function AmzOrderComplete() {
    var i = 0

    chrome.storage.sync.get(['UrunID', 'UrunFiyat', 'NextPrice', 'CardNumber'], function (item) {
        // if($("input[type=radio][value=no-rush-delivery]"))
        // $("input[type=radio][value=no-rush-delivery]").prop("checked",true);$("input[type=radio][value=no-rush-delivery]").click();$("input[type=radio][value=no-rush-delivery]").trigger('click');
        // console.log("AmzOrderComplete()");

        setInterval(function () {
            $('input[type=radio][value=no-rush-delivery]').prop('checked', true)
            $('input[type=radio][value=no-rush-delivery]').click()
            $('input[type=radio][value=no-rush-delivery]').trigger('click')
            console.log('AmzOrderComplete()' + i + zarar)
            i++
            chrome.storage.local.get(['AdresBilgileri'], function (item) {
                var data = item.AdresBilgileri
                // if(data.Name == nm)
                // {
                // $("input[type=submit][aria-labelledby=orderSummaryPrimaryActionBtn-announce]").click();
                // $("input[type=submit][aria-labelledby=orderSummaryPrimaryActionBtn-announce]").trigger('click');
                // }
                //else
                //UrunZararYaz();
            })
            var AdresError = 'An error occurred setting your shipping address. Please try again.'
            var ErrorText = $('.a-alert-content').text()
            var AdresErrorDurum = ErrorText.indexOf(AdresError) !== -1

            if (AdresErrorDurum) {
                $('input[type=submit][aria-labelledby=orderSummaryPrimaryActionBtn-announce]').click()
                $('input[type=submit][aria-labelledby=orderSummaryPrimaryActionBtn-announce]').trigger('click')
            }

            var AdresError1 = 'There was a problem with some of the items in your order (see below for more information):'
            var ErrorText1 = $('.a-color-error').text()
            var AdresErrorDurum1 = ErrorText1.indexOf(AdresError1) !== -1
            if (AdresErrorDurum1) {
                //HataKontrolYap(1, checkError1.trim());
                //console.log("Hata var:" + checkError.trim());
                UrunAl(1)
                SekmeKapat(2)
            }
            if (i == 5) {
                $('input[type=submit][aria-labelledby=orderSummaryPrimaryActionBtn-announce]').click()
                $('input[type=submit][aria-labelledby=orderSummaryPrimaryActionBtn-announce]').trigger('click')
            }
            if (i == 10 || i == 20 || (i == 30 && zarar == 0)) {
                $('input[type=radio][value=no-rush-delivery]').prop('checked', true)
                $('input[type=radio][value=no-rush-delivery]').click()
                $('input[type=radio][value=no-rush-delivery]').trigger('click')
                $('.tikladim2').click()
                $('.tikladim2').trigger('click')
                $('.tikladim1').click()
                $('.tikladim1').trigger('click')
                $('#submitOrderButtonId > span > input').click()
            }
        }, 3000)
        setTimeout(function () {
            waitForElement('#subtotals-marketplace-spp-bottom > span', function () {
                var LastPrice = $('#subtotals-marketplace-spp-bottom > span').text().split('$')['1']
                var DLastPrice = parseFloat(LastPrice)
                var DUrunFiyat = parseFloat(item.UrunFiyat)
                var DNextPrice = parseFloat(item.NextPrice)
                console.log(DLastPrice)
                console.log(DUrunFiyat)
                console.log(DNextPrice)
                if (DLastPrice <= DUrunFiyat || DLastPrice <= DNextPrice) {
                    chrome.storage.sync.set(
                        {
                            Durum: 'SiparisTamamla',
                            DLastPrice: DLastPrice,
                        },
                        function () {
                            // $("#submitOrderButtonId > span > input").addClass("tikladim1");
                            // $("#submitOrderButtonId > span > input").click();
                            // $("#submitOrderButtonId > span > input").trigger("click");

                            waitForElement('#submitOrderButtonId > span', function () {
                                //var checkError = $(".a-alert-error").text();
                                var AdresError = 'There was a problem with some of the items in your order (see below for more information):'
                                var ErrorText = $('.a-color-error').text()
                                var AdresErrorDurum = ErrorText.indexOf(AdresError) !== -1
                                if (AdresErrorDurum) {
                                    HataKontrolYap(1, checkError.trim())
                                    console.log('Hata var:' + checkError.trim())
                                    UrunAl(0)
                                } else {
                                    //sipariş alınacak.
                                    // $("input[name=placeYourOrder1]").click();
                                    // $("input[name=placeYourOrder1]").trigger("click");
                                    // $("#submitOrderButtonId").addClass("isa1");
                                    // $("#submitOrderButtonId").trigger("click");
                                    // $("#submitOrderButtonId > span").click();
                                    // $("#submitOrderButtonId > span").trigger("click");
                                    // $("#submitOrderButtonId > span > input").click();
                                    // $("#submitOrderButtonId > span > input").trigger("click");
                                    // $("#submitOrderButtonId > span > input").addClass("tikladim2");
                                    // console.log("AmzOrderComplete Button tıkladım");
                                    // setTimeout(function () {
                                    // $(".tikladim2").click();
                                    // $(".tikladim2").trigger("click");
                                    // $(".tikladim1").click();
                                    // $(".tikladim1").trigger("click");
                                    // }, 10000);
                                }
                            })
                            console.log('AmzOrderComplete Button tıklanacak')
                        }
                    )
                } else {
                    console.log('AmzOrderComplete() son fiyat ile istenilen fiyattan fazla')
                    zarar++
                    UrunAl(0)
                    setTimeout(function () {
                        SekmeKapat(1)
                    }, 2000)
                }
            })
        }, 3000)
        waitForElement('.pmts-hide-cc-section', function () {
            $('input[name=ppw-instrumentRowSelection]').prop('checked', true)
            $('input[name=ppw-instrumentRowSelection]').click()
            console.log(item.CardNumber)
            $('#addCreditCardNumber').parent().parent().addClass('ekledim')
            $('#addCreditCardNumber').parent().parent().removeClass('hidden')
            $('#addCreditCardNumber').parent().parent().css('display', 'block')
            $('#addCreditCardNumber').parent().parent().show()
            // $("#existing-credit-cards-box > .payment-row").eq(0).addClass("payment-selected");
            // $("#existing-credit-cards-box > .payment-row").eq(0).children().find('input:radio[name=paymentMethod]').prop('checked', true);
            //credit card CardNumber
            setTimeout(function () {
                var placeholdername = $('.pmts-cc-number').text()
                console.log(placeholdername)
                $("input[placeholder='" + placeholdername + "']").val('4135751006434409') //item.CardNumber
                $("button:contains('Verify card')").click()
                $("button:contains('Verify card')").trigger('click')
                console.log('card number eklendi')
            }, 2000)
            waitForElement('#orderSummaryPrimaryActionBtn', function () {
                $('#orderSummaryPrimaryActionBtn > span > input').click()
                $('#orderSummaryPrimaryActionBtn > span > input').trigger('click')
                $('#orderSummaryPrimaryActionBtn > span > span').click()
                $('#orderSummaryPrimaryActionBtn > span > span').trigger('click')
                console.log('continue-top tıkladım!')
            })

            console.log('card number tıkladım!')
        })
    })
}

var AmzOrderCompleteCheckCount = 0

function AmzOrderCompleteCheck() {
    if (AmzOrderCompleteCheckCount < 2) {
        setTimeout(function () {
            OriginalAddressCheck()
            console.log('OriginalAddressCheck() Tekrar')
            AmzOrderCompleteCheckCount++
        }, 2000)
    }
}

var AmzOrderCompleteCheckCount = 0

function AmzOrderCompleteCheck() {
    if (AmzOrderCompleteCheckCount < 2) {
        setTimeout(function () {
            OriginalAddressCheck()
            console.log('OriginalAddressCheck() Tekrar')
            AmzOrderCompleteCheckCount++
        }, 2000)
    }
}

function AmzSiparisTamamla() {
    chrome.storage.sync.get(['AmzSeller', 'DLastPrice'], function (item) {
        console.log('AmzSiparisTamamla()')
        var urlu = window.location.href

        if (urlu == 'https://www.amazon.com/gp/buy/duplicate-order/handlers/display.html?hasWorkingJavascript=1') {
            $('input[name=forcePlaceOrder]').click()
            $('input[name=forcePlaceOrder]').trigger('click')
        } else {
            var MagazaAdi = item.AmzSeller
            var AbeOrAmazon = 0
            var SiparisNo = QueryStringOku('orderId')
            SiparisTamamla(MagazaAdi, SiparisNo, AbeOrAmazon)
            console.log('MagazaAdi:' + MagazaAdi + ' SiparisNo:' + SiparisNo + ' AbeSaticiNo: ' + '-' + 'Son Fiyat:' + item.DLastPrice)
        }
    })

    // var SiparisNo = $("[id|='order-number']").text();
}

function getSayfa(adres) {
    var strText = null
    $.ajax({
        url: adres,
        async: false,
        dataType: 'text',
        success: function (text) {
            strText = text
        },
        error: function (http, message, exc) {
            strText = null
        },
    })

    return strText
}

function QueryStringOku(name, url) {
    if (!url) url = window.location.href
    name = name.replace(/[\[\]]/g, '\\$&')
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url)
    if (!results) return null
    if (!results[2]) return ''
    return decodeURIComponent(results[2].replace(/\+/g, ' '))
}

function SekmeKapat(sure) {
    setTimeout(function () {
        chrome.runtime.sendMessage({
            SekmeKapat: true,
        })
    }, sure * 1000)
}

function SekmeBilgileriGonder() {
    chrome.runtime.sendMessage({
        AktifSekmeBilgileri: true,
    })
}

function waitForElement(elementPath, callBack) {
    window.setTimeout(function () {
        if ($(elementPath).text().length > 0) {
            callBack(elementPath, $(elementPath))
        } else {
            waitForElement(elementPath, callBack)
        }
    }, 100)
}

function ClearData() {
    AppLog(log)
    AppLogGonder()
    sessionStorage.clear()
    chrome.runtime.sendMessage({
        LinkHata: 'LinkteError',
        YeniSekme: true,
    })
    clearTimeout(HataKontrol)
}

function AppLogGonder() {
    chrome.runtime.sendMessage({
        HataDurum: HataDurum,
        isStarted: isStarted,
        AppLog: logs,
    })
}

function AppLog(log) {
    var time = new Date().toLocaleString()
    var test = log + ' - ' + time
    var loglar = logs
    if (loglar.length < 6) {
        loglar.push(test)
    } else {
        loglar.splice(0, 1)
        loglar.push(test)
    }
    logs = loglar
    localStorage.setItem('LocalStorageAppLog', JSON.stringify(logs))
    chrome.storage.sync.set(
        {
            AppLog: test,
        },
        function () {}
    )
}

function SayfaGit(adres, time) {
    setTimeout(function () {
        window.location.href = adres
    }, parseInt(time) * 1000)
}

function BellekSil() {
    chrome.storage.sync.remove(['isStarted', 'Durum'], function () {})
}

var HataKontrol

function HataKontrolYap(time, msj2) {
    HataKontrol = setTimeout(function () {
        //location.reload();
        chrome.storage.sync.get(['isStarted', 'PcName', 'UygulamaAdi', 'Durum', 'UrunID', 'MagazaAdi'], function (item) {
            var aciklama = ''
            if (msj2 == undefined) {
                aciklama = ''
            } else {
                aciklama = msj2
            }
            var msj = `Bilgisayar: ${item.PcName} Mağaza Adı: ${item.MagazaAdi}  Durum: ${item.Durum} iken extension çalışmayı durdurdu! ${aciklama}`
            var datam = {
                ID: item.UrunID,
                tip: 'newOrderBreak',
                mesaj: msj,
            }
            console.log(msj)
            if (msj2 == undefined) {
                chrome.runtime.sendMessage({
                    HataYenile: true,
                })

                UrunGetir()
            }

            // $.ajax({
            // type: "post",
            // url: "https://www.andromedaworkspace.com/Extension/ajaxCall",
            // beforeSend: function (xhr) {
            // xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
            // },
            // cache: false,
            // dataType: "json",
            // data: datam,
            // success: function (cevap) {

            // if (cevap.hata == 0) {
            // console.log("Hata: Hata Bilgisi Gönderilemedi!");

            // } else {
            // if (cevap.result) {
            // console.log(cevap.result);
            // setTimeout(function () {

            // }, 3000);

            // }
            // }
            // console.log("Hata Bilgisi  Gönder Response!");
            // },
            // error: function (req, textStatus, errorThrown) {
            // console.log('Ooops, something happened: ' + textStatus + ' ' + errorThrown);
            // }
            // });
        })
    }, parseInt(time) * 1000)
}

function getRandomInt(max) {
    return Math.floor(Math.random() * (max - 0 + 1)) + 0
}

function SekmeAc(link) {
    setTimeout(function () {
        console.log('Sekme Açılıyor: ' + link)
        chrome.runtime.sendMessage({
            YeniSekme: true,
            Url: link,
        })
    }, 1000)
}

//localStorage.removeItem("KontrolUrl1");
//localStorage.removeItem("KontrolUrl2");
// chrome.storage.local.set({
// 'SekmeCount': 0
// }, function () {
// });
// HataKontrolYap(250);
// chrome.storage.local.get(["RunCount"], function (item) {
// RunCount=item.RunCount
// });
// console.log(RunCount+1);

// chrome.storage.sync.set({
// "UrunID": "",
// "UrunGetirildi": true,
// "Durum": "TypeKontrol",
// "UrunFiyat": "",
// "AbeUrl": "",
// "AmazonUrl": "",
// "KontrolUrl1Hata": 0,
// "KontrolUrl2Hata": 0,
// "KontrolUrl1": "",
// "KontrolUrl2": "",
// "AdresEklendi":false,
// "RunCount": RunCount+1
// }, function () {
// linkKontrolCount = 0;
// urunKontrolCount = 0;
// var link1 = `https://www.amazon.com/Bedtime-Originals-Twinkle-Elephant-Plush/dp/B0771V1JZX`;
// //var link2 = `https://www.ebay.com/itm/Fluffy-Rugs-Anti-Skid-Shaggy-Area-Rug-Carpet-Dining-Room-Home-Bedroom-Floor-Mat/383128436979`;
// var link3 = `https://www.walmart.com/ip/Safavieh-California-Solid-Plush-Shag-Area-Rug-or-Runner/17691964`;
// var link4 = `https://www.wayfair.com/rugs/pdp/calvin-klein-la-hand-woven-shag-cobalt-blue-area-rug-drqh1001.html`;
// var link5 = `https://www.overstock.com/Home-Garden/Safavieh-Madison-Bohemian-Vintage-Cream-Multi-Distressed-Rug-8-x-10/12659869/product.html`;
// var link6 = `https://www.homedepot.com/p/Foss-Unbound-Smoke-Gray-Ribbed-6-ft-x-8-ft-Indoor-Outdoor-Area-Rug-CP45N41PJ1VH/202800194`;
// var link7 = `https://markandday.com/collections/deals-of-month/products/cambrai-modern-white-rug`;
// var link8 = `https://boutiquerugs.com/venezia-vnz-2309-area-rug/?button=shop_now`;
// // if(data.KontrolUrl1 == data.KontrolUrl2)
// // {
// // chrome.storage.sync.set({
// // "Durum": "FiyatKontrol"
// // },function () {
// // SiparisLinkleriGetir(data.ID, data.AmazonUrl, data.AbeUrl);
// // });

// // }else{
// SekmeAc(link1);
// //SekmeAc(link2);
// SekmeAc(link3);
// SekmeAc(link4);
// SekmeAc(link5);
// SekmeAc(link6);
// SekmeAc(link7);
// SekmeAc(link8);

// // AmazonUrl = data.AmazonUrl;
// // AbeUrl = data.AbeUrl;
// // console.log("Sekmeler Açılacak!");
// // if (host == "www.amazon.com" || host == "www.abebooks.com") {
// // SekmeKapat(2);
// // }
// //}
// });
