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);
    }
})

function HataKontrolYap(time, msj2) {
    HataKontrol = setTimeout(function () {
        //location.reload();
        chrome.storage.local.get(['isStarted', 'PcName', '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)
            var host = window.location.host
            chrome.runtime.sendMessage({
                HataYenile: true,
            })
        })
    }, parseInt(time) * 1000)
}

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++
                if (linkKontrolCount == 2) {
                    setTimeout(function () {
                        UrlKontrolYap()
                    }, 2000)
                }
            }
        } else if (key == 'AmzUrunList') {
            storageChange = changes[key]
            if (storageChange.newValue != undefined && storageChange.newValue != null) {
                urunKontrolCount++
                if (urunKontrolCount >= 2) {
                    setTimeout(function () {
                        console.log(' UrunListeleriniGonder(); onchanged çağrıldı')
                        //UrunListeleriniGonder();
                    }, 2000)
                }
            } else {
                UrunZararYaz()
            }
        } else {
        }
    }
})

$(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
                    //alert(AbeUrl);

                    var urll = window.location.href
                    // if(urll=="https://www.amazon.com/gp/errors/404.html")
                    // {
                    // UrunZararYaz();
                    // }
                    if (host == 'clinic.amazon.com' || host == 'health.amazon.com') {
                        UrunZararYaz()
                    }
                    if (host != 'www.amazon.com' && host != 'www.thriftbooks.com') {
                        if (item.UrunGetirildi == false) {
                            //KartBilgisiGetir(item.MagazaAdi);

                            UrunGetir()
                            SekmeBilgileriGonder()
                            //HataKontrolYap(250)
                        } 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)
                        } else if (item.Durum == 'FiyatKontrol') {
                            if (host == 'www.jqueryscript.net') {
                                UrunGetir()
                            }
                            console.log('Şuan yapılan işlem: ' + item.Durum)
                        } else {
                            console.log('düşün')
                        }
                    } else {
                        //HataKontrolYap(275);
                        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'))
                            setTimeout(function () {
                                var TipKontrolYap =
                                    LinkKontrolSayfasi == 1
                                        ? BirinciLinkKontrol(KontrolUrl2, KontrolUrl1Hata)
                                        : IkinciLinkKontrol(KontrolUrl1, KontrolUrl2Hata)
                            }, 500)
                        } else if (item.Durum == 'FiyatKontrol') {
                            HataKontrolYap(250)
                            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 () {
                                AmazonFiyatKontrol(Fiyat, AmzPageCount, AmazonUrl)
                                console.log('FiyatKontrolYap')
                            }, 500)

                            //}else{
                            //AbeFiyatKontrol(Fiyat, AbePageCount, AbeUrl);
                            //}
                        } 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' ? AbeAdresEkle() : 'AbeAdresSilme()'
                                    }, 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 {
                                    if (document.querySelector('#submitOrderButtonId > span > input')) {
                                        AmzOrderComplete()
                                    } else {
                                        setTimeout(function () {
                                            var HangiSayfa =
                                                UrunSatinAlmaSayfasi == 'Abe'
                                                    ? AbeUrunAl(item.UrunFiyat)
                                                    : AmzUrunAl(item.UrunFiyat)
                                        }, 500)
                                    }
                                }
                            } else if (window.location.href == 'https://www.thriftbooks.com/shopping-cart/') {
                                AbeBasketBosalt()
                            } else if (window.location.href == 'https://www.thriftbooks.com/checkout/shipping/') {
                                AbeAdresEkle()
                            } else if (window.location.href == 'https://www.thriftbooks.com/checkout/payment/') {
                                AbeSaveBilling()
                            } else if (
                                window.location.href == 'https://www.thriftbooks.com/checkout/placeorder/quick/' ||
                                window.location.href == 'https://www.thriftbooks.com/checkout/placeorder/'
                            ) {
                                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' ||
                                window.location.pathname.indexOf('/gp/cart/view.html') >= 0
                            ) {
                                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')
                                if ($('.welcome-msg')) UrunZararYaz()
                            } else {
                                var path = window.location.pathname.toString()
                                var NotAdded = 'item-dispatch'
                                var NotAddedDurum = path.indexOf(NotAdded) !== -1
                                if (NotAddedDurum) {
                                    AmzItemNotAdded()
                                } else {
                                    if (window.location.pathname == '/gp/buy/spc/handlers/display.html') {
                                        AmzOrderComplete()
                                    } else {
                                        if (document.querySelector('#submitOrderButtonId > span > input')) {
                                            AmzOrderComplete()
                                        } else if (
                                            document.querySelector('#orderSummaryPrimaryActionBtn > span > input')
                                        ) {
                                            AmzOrderComplete()
                                        } else {
                                            console.log('hiç biri')
                                            //UrunZararYaz()
                                        }
                                    }
                                }
                            }
                        } else if (item.Durum == 'SiparisTamamla') {
                            var Sayfa = QueryStringOku('PgNm')
                            var SiparisTamamla = QueryStringOku('SiparisTamamla')
                            if (host == 'www.thriftbooks.com') {
                                Sayfa = 'Abe'
                                SiparisTamamla = 'Tamamla'
                            } else {
                                Sayfa = QueryStringOku('PgNm')
                            }

                            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()
                            else if (window.location.pathname == '/gp/css/order-history') AmzOrderInfoGet()
                        } else if (item.Durum == 'AppStarted') {
                            if (host != 'www.jqueryscript.net') {
                                SekmeAc(null)
                                SekmeKapat(1)
                            }
                        }
                    }
                }
            }, parseInt(item.RequestTime) * 1000)
        }
    )
})

function UrunGetir() {
    var host = window.location.host
    setTimeout(function () {
        chrome.storage.sync.get(['MagazaAdi', 'PcName', 'isStarted', 'ApiUrl'], function (item) {
            if (item.isStarted) {
                //clearTimeout(HataKontrol);
                //HataKontrolYap(75);
                console.log('Ürün Getirilecek!')
                localStorage.clear()
                localStorage.removeItem('LSAmazonUrunList')
                var datam = {
                    magazaDeger: item.MagazaAdi,
                    tip: 'newOrderStart',
                    PCAd: item.PcName,
                }
                console.log(datam)
                console.log(datam.magazaDeger + ' için sipariş alınacak!')
                $.ajax({
                    type: 'post',
                    url: item.ApiUrl + 'ExtensionWebServis/ajaxCall',
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
                    },
                    cache: false,
                    dataType: 'json',
                    data: datam,
                    timeout: 500000,
                    success: function (cevap) {
                        console.log(cevap)
                        if (cevap.hata == 0) {
                            chrome.storage.sync.set(
                                {
                                    UrunGetirildi: false,
                                    Durum: 'AppStarted',
                                },
                                function () {
                                    //UrunGetir()
                                    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.'
                                    HataKontrolYap(1, text)

                                    chrome.runtime.sendMessage({
                                        YenidenBaslat: true,
                                    })
                                    if (host == 'www.amazon.com' || host == 'www.thriftbooks.com') {
                                        SekmeKapat(2)
                                    }
                                }
                            )
                        } else {
                            if (cevap.result) {
                                console.log(cevap.result)
                                //console.table(cevap.result);
                                var data = cevap.result
                                if (true) {
                                    localStorage.clear()
                                    localStorage.removeItem('LSAmazonUrunList')
                                    chrome.storage.sync.set(
                                        {
                                            UrunID: data.ID,
                                            UrunGetirildi: true,
                                            Durum: 'FiyatKontrol',
                                            UrunFiyat: data.Fiyat,
                                            AbeUrl: data.ThriftBookUrl,
                                            AmazonUrl: data.AmazonUrl,
                                            UrunAdet: data.Adet,
                                            KontrolUrl1Hata: 0,
                                            KontrolUrl2Hata: 0,
                                            KontrolUrl1: '',
                                            KontrolUrl2: '',
                                            AdresEklendi: false,
                                        },
                                        function () {
                                            linkKontrolCount = 0
                                            urunKontrolCount = 0
                                            var link1 = `${data.KontrolUrl1}?&Validate=1`
                                            var link2 = `${data.KontrolUrl2}?&Validate=2`
                                            // if(data.KontrolUrl1 == data.KontrolUrl2)
                                            // {
                                            // chrome.storage.sync.set({
                                            // "Durum": "FiyatKontrol"
                                            // },function () {
                                            // SiparisLinkleriGetir(data.ID, data.AmazonUrl, data.AbeUrl);
                                            // });

                                            // }else{
                                            console.table(data)
                                            console.log(data.AmazonUrl)
                                            console.log(data.Fiyat + 'Alış fiyatı!!!!!')
                                            SekmeAc(data.AmazonUrl)
                                            //SekmeAc(link2);
                                            AmazonUrl = data.AmazonUrl
                                            AbeUrl = data.AbeUrl

                                            console.log('Sekmeler Açılacak!')

                                            if (host == 'www.amazon.com' || host == 'www.thriftbooks.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)
                    },
                })
            }
        })
    }, 2000)
}

function BirinciLinkKontrol(KontrolUrl2, Sorgu) {
    var deger = ''
    var mediaTab = $('#mediaTabsGroup')
    var tmmSwatches = $('#tmmSwatches > ul > li.swatchElement.selected')
    var c = $('#productTitle').text()
    chrome.storage.sync.get(['KontrolUrl1', 'KontrolUrl2', 'UrunID', 'AbeUrl', 'AmazonUrl'], function (item) {
        console.log(item.KontrolUrl1 + ' ' + item.KontrolUrl2)
    })
    console.log(KontrolUrl2)
    if (mediaTab.length > 0) {
        var a = $('ul#mediaTabs_tabSet').find('.a-active').children().find('.mediaTab_title').text()
        deger = a
    } else if (tmmSwatches.length > 0) {
        var b = $('#tmmSwatches > ul > li.swatchElement.selected')
            .children()
            .children()
            .children()
            .children()
            .children()
            .eq(0)
            .text()
        deger = b
    } else {
        var durum = c.indexOf(KontrolUrl2) !== -1
        deger = durum == true ? KontrolUrl2 : 'EşitDegilKontrolURL1'
    }

    if (deger.length == 0) {
        if (Sorgu < 10) {
            var sorguCount = Sorgu + 1
            chrome.storage.sync.set(
                {
                    KontrolUrl1Hata: sorguCount,
                },
                function () {
                    setTimeout(function () {
                        console.log('Sayfa Yeniden Yükledim!')
                        window.location.reload()
                    }, 2000)
                }
            )
        } else {
            deger = 'KontrolUrl1' + Sorgu
            chrome.storage.sync.set(
                {
                    KontrolUrl1: deger,
                },
                function () {
                    console.log('Birinci url kontrol edildi: ' + deger)
                    SekmeKapat(1)
                }
            )
        }
    } else {
        chrome.storage.sync.set(
            {
                KontrolUrl1: deger,
                Titles: c,
            },
            function () {
                console.log('Birinci url kontrol edildi: ' + deger)
                SekmeKapat(1)
            }
        )
    }
}

function IkinciLinkKontrol(KontrolUrl1, Sorgu) {
    setTimeout(function () {
        var deger = ''
        var mediaTab = $('#mediaTabsGroup')
        var tmmSwatches = $('#tmmSwatches')
        if (mediaTab.length > 0) {
            var a = $('ul#mediaTabs_tabSet').find('.a-active').children().find('.mediaTab_title').text()
            deger = a
            chrome.storage.sync.get(['KontrolUrl1', 'Titles'], function (item) {
                console.log(item.KontrolUrl1 + 'aliosman' + item.Titles)
                console.log(deger)
                console.log(deger)
                if (deger != item.KontrolUrl1 && item.KontrolUrl1 != 'Mass Market Paperback') {
                    var durum = item.Titles.indexOf(deger) !== -1
                    console.log(durum)
                    if (durum && item.KontrolUrl1 != '') {
                        deger = durum == true ? item.KontrolUrl1 : 'EşitDegilKontrolURL2'
                    }
                    console.log(item.KontrolUrl1 + 'am' + deger)
                    chrome.storage.sync.set(
                        {
                            KontrolUrl2: deger,
                        },
                        function () {
                            console.log('İkinci url kontrol edildi: ' + deger)
                            SekmeKapat(1)
                        }
                    )
                }
            })
        } else if (tmmSwatches.length > 0) {
            var b = $('#tmmSwatches > ul > li.swatchElement.selected')
                .children()
                .children()
                .children()
                .children()
                .children()
                .eq(0)
                .text()
            deger = b
            chrome.storage.sync.get(['KontrolUrl1', 'Titles'], function (item) {
                console.log(item.KontrolUrl1 + 'aliosman' + item.Titles)
                console.log(deger)
                console.log(deger)
                if (deger != item.KontrolUrl1 && item.KontrolUrl1 != 'Mass Market Paperback') {
                    var durum = item.Titles.indexOf(deger) !== -1
                    console.log(durum)
                    if (durum && item.KontrolUrl1 != '') {
                        deger = durum == true ? item.KontrolUrl1 : 'EşitDegilKontrolURL2'
                    }
                    console.log(item.KontrolUrl1 + 'am' + deger)
                    chrome.storage.sync.set(
                        {
                            KontrolUrl2: deger,
                        },
                        function () {
                            console.log('İkinci url kontrol edildi: ' + deger)
                            SekmeKapat(1)
                        }
                    )
                }
            })
        } else {
            var c = $('#productTitle').text()
            var durum = c.indexOf(KontrolUrl1) !== -1
            deger = durum == true ? KontrolUrl1 : 'EşitDegilKontrolURL2'
        }

        if (deger.length == 0) {
            if (Sorgu < 10) {
                var sorguCount = Sorgu + 1
                chrome.storage.sync.set(
                    {
                        KontrolUrl2Hata: sorguCount,
                    },
                    function () {
                        setTimeout(function () {
                            console.log('Sayfa Yeniden Yükledim!')
                            window.location.reload()
                        }, 2000)
                    }
                )
            } else {
                deger = 'KontrolUrl2' + Sorgu
                chrome.storage.sync.set(
                    {
                        KontrolUrl2: deger,
                    },
                    function () {
                        console.log('İkinci url kontrol edildi: ' + deger)
                        SekmeKapat(1)
                    }
                )
            }
        } else {
            chrome.storage.sync.set(
                {
                    KontrolUrl2: deger,
                },
                function () {
                    console.log('İkinci url kontrol edildi: ' + deger)
                    SekmeKapat(1)
                }
            )
        }
    }, 2000)
}

function UrlKontrolYap() {
    var host = window.location.host
    if (host != 'www.amazon.com' && host != 'www.thriftbooks.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 HataliUrun(id) {
    chrome.storage.sync.get(['ApiUrl'], function (item) {
        console.log('Hatalı Ürün bildirilecek!')
        $.ajax({
            type: 'post',
            url: item.ApiUrl + 'ExtensionWebServis/ajaxCall',
            beforeSend: function (xhr) {
                xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
            },
            cache: false,
            dataType: 'json',
            timeout: 500000,
            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)
    AbeUrl = window.location.href
    chrome.storage.local.set({
        AbeUrl: window.location.href,
    })
    var UrunList = localStorage.getItem('LSAbeUrunList')
    console.log(UrunList)
    //alert(AbeUrl);
    if (UrunList != undefined) {
        AbeUrunList = JSON.parse(UrunList)
    }
    var FiyatKontrolTamamlandi = true
    var DFiyat = parseFloat(fiyat)
    var UrunFiyat = ''
    if ($('span.price').length > 0 || $('.is-selected.is-compact').length > 0) UrunFiyat = $('span.price').text()
    else UrunFiyat = $('.is-selected.is-compact > div:nth-child(2) > span').text().split('$')[1]

    if (UrunFiyat == '') {
        console.log('Verileri Gonder')
        console.table(AbeUrunList)
        var isbn = QueryStringOku('isbn')
        chrome.storage.local.set({}, function () {
            console.log('AbeUrunList kontrol edildi: ')
            localStorage.removeItem('LSAbeUrunList')
            SekmeKapat(1)
        })
    }

    var Price = UrunFiyat
    var condition = $('.is-selected.is-compact > div:nth-child(1)').text()
    if (DFiyat > Price && condition == 'Like New') {
        var isAvailable = $(this).find('.bookseller-info').next('div').attr('class')
        console.log(isAvailable)

        var c = '0' //$(this).find(".clear-all").children().eq(1).text().split("Condition:")[1];
        var Condition = condition //c != undefined ? c.split(".")[0].trim() : "-";
        var Condition = condition //c != undefined ? c.split(".")[0].trim() : "-";
        var Seller = '0' //$(this).find(".bookseller-info").children().eq(0).children().text().trim();
        var Ratings = '0' // $(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 = '0' //$(this).find(".srp-item-shipping-dest").text().trim();
        // var SellerHref = $(this).find(".shipping").next().next().children().eq(0).attr('href');
        var SellerHref = '0' // $(this).find(".srp-item-buybox ").children().last().children().last().attr('href');
        var SellerID = '0' //SellerHref.split(/[=&]/)[2];
        var ShippingDate = []
        var SellerLink = '0' // "https://www.abebooks.com/servlet/ShipRates?vid=" + SellerID;
        var gelenData = '0' // getSayfa(SellerLink);
        var parser = new DOMParser()
        var htmlDoc = parser.parseFromString(gelenData, 'text/html')
        var normal = '0' //$(htmlDoc).find("tbody > tr").eq(0).find("td").eq(1).text();

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

        console.log('index: ' + index)

        FiyatKontrolTamamlandi = true
        //localStorage.setItem('LSAbeUrunList', JSON.stringify(AbeUrunList));
    } 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 TopPrice() {
    var index = -1
    var UrunFiyat = $('#aod-pinned-offer').find('.a-offscreen').text().trim().substr(1).replace(',', '')
    console.log(UrunFiyat)
    if (document.querySelector('#pinned-offer-top-id > div:nth-child(3) > span > span'))
        var KargoFiyat = document
            .querySelector('#pinned-offer-top-id > div:nth-child(3) > span > span')
            .textContent.split(' ')
    else var KargoFiyat = 0
    console.log(KargoFiyat.length)
    if (KargoFiyat.length > 1) KargoFiyat = KargoFiyat[1].trim().substr(1).replace(',', '')
    console.log(KargoFiyat)
    var DUrunFiyat = parseFloat(UrunFiyat)
    var DKargoFiyat = KargoFiyat.length > 1 ? parseFloat(KargoFiyat.replace(',', '')) : 0
    var Price = DUrunFiyat + DKargoFiyat
    var Condition = $('#aod-pinned-offer').find('#aod-offer-heading > h5').text().replace(/\s/g, '').trim()
    var Delivery = $('#aod-pinned-offer')
        .find('#aod-fasttrack-0 #delivery-message > b')
        .text()
        .split('\n')
        .map((item) => item.trim())
        .join(' ')
        .trim()
    var isPrime = $('#aod-pinned-offer')
        .find('#aod-offer-shipsFrom > div > div > div.a-fixed-left-grid-col.a-col-right > span')
        .text()
    if (isPrime == 'Amazon.com') isPrime = true
    else isPrime = false
    var Seller = $('#aod-pinned-offer')
        .find('#aod-offer-soldBy > div > div > div.a-fixed-left-grid-col.a-col-right > a')
        .text()
        .trim()
    var Positive = $('#aod-pinned-offer').find('#seller-rating-count-\\{iter\\} > span').text().split('%')
    if (Positive.length > 0) Positive = Positive[0].split(')')[1]
    var r = $('#aod-pinned-offer').find('#seller-rating-count-\\{iter\\} > span').text().split('%')
    if (r.length > 0) r = r[0].split(')')[0].split(' ')[0].split('(')[1]
    var Ratings = r != undefined ? r : '-'
    Price = Price.toFixed(2)
    if (isPrime && Seller == '') Seller = 'Amazon.com'

    console.log(isPrime)
    console.log(Condition)
    console.log(Delivery)
    console.log(Seller)
    console.log(Positive)
    console.log(Price)
    console.log(Ratings)
    var item = {
        index,
        isPrime,
        Condition,
        Delivery,
        Seller,
        Positive,
        Ratings,
        Price,
        Page: 0,
    }

    AmzUrunList.push(item)
    console.table(AmzUrunList)
}

function AmazonFiyatKontrol(fiyat, AmzPageCount, AmazonUrl) {
    var Condition = QueryStringOku('condition')

    setTimeout(function () {
        if (Condition == 'new') {
            if (
                document.querySelector(
                    '#tmmSwatches > ul > li.swatchElement.selected > span > span:nth-child(3) > span.olp-new.olp-link > span > a'
                )
            )
                document
                    .querySelector(
                        '#tmmSwatches > ul > li.swatchElement.selected > span > span:nth-child(3) > span.olp-new.olp-link > span > a'
                    )
                    .click()
            else if (
                document.querySelector(
                    '#mediaOlp > div > div > div > div.a-fixed-right-grid-col.accordion-row-left-content.a-col-left > div:nth-child(2) > span > a'
                )
            ) {
                $(
                    '#mediaOlp > div > div > div > div.a-fixed-right-grid-col.accordion-row-left-content.a-col-left > div:nth-child(2) > span > a'
                ).each(function () {
                    console.log($(this).attr('href'))
                    if ($(this).attr('href').indexOf('condition=new') >= 0) {
                        $(this).click()
                    }
                })
            }
        } else {
            if (
                document.querySelector(
                    '#tmmSwatches > ul > li.swatchElement.selected > span > span:nth-child(3) > span.olp-used.olp-link > span > a'
                )
            )
                document
                    .querySelector(
                        '#tmmSwatches > ul > li.swatchElement.selected > span > span:nth-child(3) > span.olp-used.olp-link > span > a'
                    )
                    .click()
            else if (
                document.querySelector(
                    '#mediaOlp > div > div > div > div.a-fixed-right-grid-col.accordion-row-left-content.a-col-left > div:nth-child(2) > span > a'
                )
            ) {
                $(
                    '#mediaOlp > div > div > div > div.a-fixed-right-grid-col.accordion-row-left-content.a-col-left > div:nth-child(2) > span > a'
                ).each(function () {
                    console.log($(this).attr('href'))
                    if ($(this).attr('href').indexOf('condition=used') >= 0) {
                        $(this).click()
                    }
                })
                // $("#mediaOlp div.a-fixed-right-grid-col.accordion-row-left-content.a-col-left  div:nth-child(2) span a").each(function(){
                // console.log($(this).attr('href').indexOf("condition=used"))
                // if($(this).attr('href').indexOf("condition=used") >= 0) {
                // $(this).click();
                // }

                // });
            }
        }
    }, 1000)

    waitForElement('#aod-container', function () {
        setTimeout(function () {
            if (Condition != 'new') {
                console.log(Condition)

                if (document.querySelector('#usedGood > div > label > input[type=checkbox]').checked)
                    document.querySelector('#usedGood').click()
                if (document.querySelector('#usedVeryGood > div > label > input[type=checkbox]').checked)
                    document.querySelector('#usedVeryGood').click()
                if (document.querySelector('#usedAcceptable > div > label > input[type=checkbox]').checked)
                    document.querySelector('#usedAcceptable').click()
                if (document.querySelector('#usedLikeNew > div > label > input[type=checkbox]').checked)
                    document.querySelector('#usedLikeNew').click()

                if (!document.querySelector('#' + Condition + ' > div > label > input[type=checkbox]').checked)
                    document.querySelector('#' + Condition).click()
            }
        }, 5000)
        setTimeout(function () {
            if (
                $('#tmmSwatches > ul > li.swatchElement.selected.resizedSwatchElement  span.olp-new.olp-link  span  a')
                    .length
            ) {
                var sellerCount = $(
                    '#tmmSwatches > ul > li.swatchElement.selected.resizedSwatchElement  span.olp-new.olp-link  span  a'
                )
                    .text()
                    .trim()
                    .split('New from')[0]
                    .trim()
                var newPrice = $(
                    '#tmmSwatches > ul > li.swatchElement.selected.resizedSwatchElement  span.olp-new.olp-link  span  a'
                )
                    .text()
                    .trim()
                    .split('New from')[1]
                    .trim()
            }
            if (
                $(
                    '#rpi-attribute-book_details-isbn10  div.a-section.a-spacing-none.a-text-center.rpi-attribute-value  span'
                ).length
            ) {
                var Isbn10 = $(
                    '#rpi-attribute-book_details-isbn10  div.a-section.a-spacing-none.a-text-center.rpi-attribute-value  span'
                )
                    .text()
                    .trim()
            }

            if (
                $(
                    '#rpi-attribute-book_details-isbn13  div.a-section.a-spacing-none.a-text-center.rpi-attribute-value  span'
                ).length
            ) {
                var Isbn13 = $(
                    '#rpi-attribute-book_details-isbn13  div.a-section.a-spacing-none.a-text-center.rpi-attribute-value  span'
                )
                    .text()
                    .trim()
            }
            var buyBoxNew = 0
            if ($('#buyBoxAccordion #newAccordionRow').length) {
                buyBoxNew = 1
            }
            var rank = 0
            if ($('#detailBulletsWrapper_feature_div')) {
                $('#detailBulletsWrapper_feature_div > ul').each(function () {
                    if ($(this).text().trim().indexOf('Best Sellers Rank') != -1) {
                        var text = $(this).find('li > span').text()
                        var splitedText = text.split('in Books')
                        if (splitedText.length > 1) {
                            var sText = splitedText[0].split('Best Sellers Rank:')
                            if (sText.length > 0) {
                                rank = sText[1].trim().split('#')[1]
                            }
                        }
                    }
                })
            }
            console.log(
                'rank:' +
                    rank +
                    'sellerCount:' +
                    sellerCount +
                    'newPrice:' +
                    newPrice +
                    'Isbn10:' +
                    Isbn10 +
                    'Isbn13:' +
                    Isbn13 +
                    'buyBoxNew' +
                    buyBoxNew
            )
            //TopPrice();
            var UrunList = localStorage.getItem('LSAmazonUrunList')
            if (UrunList != undefined) {
                AmzUrunList = JSON.parse(UrunList)
            }
            var liste = $('#aod-offer-list #aod-offer')
            var listeItemCount = parseInt($('#aod-offer-list #aod-offer').length) - 1

            var FiyatKontrolTamamlandi = true
            liste.each(function (index) {
                // $(this).find(".olpFastTrack").find("a").parent().remove("").end();
                var UrunFiyat = $(this).find('.a-offscreen').text().trim().substr(1).replace(',', '')
                console.log(
                    $(this)
                        .find('#mir-layout-DELIVERY_BLOCK-slot-PRIMARY_DELIVERY_MESSAGE_LARGE')
                        .find('span')
                        .attr('data-csa-c-delivery-price')
                )
                if (
                    $(this)
                        .find('#mir-layout-DELIVERY_BLOCK-slot-PRIMARY_DELIVERY_MESSAGE_LARGE')
                        .find('span')
                        .attr('data-csa-c-delivery-price')
                ) {
                    var KargoFiyat = $(this)
                        .find('#mir-layout-DELIVERY_BLOCK-slot-PRIMARY_DELIVERY_MESSAGE_LARGE')
                        .find('span')
                        .attr('data-csa-c-delivery-price')
                        .split('$')
                } else {
                    var KargoFiyat = 0.0
                }
                console.log('Kargo: ' + KargoFiyat)
                if (KargoFiyat.length > 1 || KargoFiyat[0] !== 'FREE') KargoFiyat = KargoFiyat[1] ?? KargoFiyat
                var DFiyat = parseFloat(fiyat)
                var DUrunFiyat = parseFloat(UrunFiyat)
                var DKargoFiyat = KargoFiyat.length > 1 ? parseFloat(KargoFiyat) : 0
                if (isNaN(DKargoFiyat)) DKargoFiyat = 0.0
                var Price = DUrunFiyat + DKargoFiyat
                //console.log(Price + "---" + DUrunFiyat + "---" + DKargoFiyat);
                //if (DFiyat > Price) {
                var Condition = $(this).find('#aod-offer-heading > h5').text().replace(/\s/g, '').trim()
                var ConditionDesc = $(this).find('#condition-text-block-title span.expandable-expanded-text').text()

                var Delivery = $(this)
                    .find('#delivery-message > b')
                    .text()
                    .split('\n')
                    .map((item) => item.trim())
                    .join(' ')
                    .trim()
                if (Delivery == '') {
                    Delivery = $(this)
                        .find('#mir-layout-DELIVERY_BLOCK-slot-PRIMARY_DELIVERY_MESSAGE_LARGE > span > span')
                        .text()
                }
                var isPrime = $(this)
                    .find('#aod-offer-shipsFrom > div > div > div.a-fixed-left-grid-col.a-col-right > span')
                    .text()
                if (isPrime == 'Amazon.com') isPrime = true
                else isPrime = false
                var Seller = $(this)
                    .find('#aod-offer-shipsFrom > div > div > div.a-fixed-left-grid-col.a-col-right > span')
                    .text()
                    .trim()
                var Positive = $(this).find('#seller-rating-count-\\{iter\\} > span').text().split('%')
                if (Positive.length > 0) Positive = Positive[0].split(')')[1]
                var r = $(this).find('#seller-rating-count-\\{iter\\} > span').text().split('%')
                if (r.length > 0) r = r[0].split(')')[0].split(' ')[0].split('(')[1]
                var Ratings = r != undefined ? r : '-'
                Price = Price.toFixed(2)

                chrome.storage.local.set(
                    {
                        Rank: rank,
                        SellerCount: sellerCount,
                        newPrice: newPrice,
                        Isbn10: Isbn10,
                        Isbn13: Isbn13,
                        buyBoxNew: buyBoxNew,
                    },
                    function () {}
                )
                var item = {
                    index,
                    isPrime,
                    Condition,
                    Delivery,
                    Seller,
                    Positive,
                    Ratings,
                    Price,
                    ConditionDesc,
                    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.table(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')

                        UrunListeleriniGonder()
                        //SekmeKapat(5);
                    }
                )
            } 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);
                    }
                )
            }
        }, 8000)
    })
}

function UrunListeleriniGonder() {
    console.log(' UrunListeleriniGonder()')

    var host = window.location.host

    if (host != 'www.thriftbooks.com') {
        let OurPrice = 0
        let MagazaAdi = ''
        chrome.storage.sync.get(['UrunID', 'PcName', 'UrunFiyat', 'ApiUrl', 'MagazaAdi'], function (item) {
            UrunID = item.UrunID
            PcName = item.PcName
            OurPrice = item.UrunFiyat
            ApiUrl = item.ApiUrl
            MagazaAdi = item.MagazaAdi
        })
        chrome.storage.local.get(
            [
                'AmzUrunList',
                'AbeUrunList',
                'PcName',
                'UrunFiyat',
                'Rank',
                'SellerCount',
                'newPrice',
                'Isbn10',
                'Isbn13',
                'buyBoxNew',
            ],
            function (item) {
                var Amazon = item.AmzUrunList
                var Abebook = []
                var orderArray = [[...Amazon]]

                var stringArray = JSON.stringify(orderArray)
                console.log(stringArray)
                var datam = {
                    ID: UrunID,
                    price: 0,
                    magazaDeger: MagazaAdi,
                    orderArray: stringArray,
                    tip: 'newOrderFiltre',
                    PCAd: PcName,
                    OurPrice: OurPrice,
                    Rank: item.Rank,
                    SaticiSayisi: item.SellerCount,
                    NewPrice: item.newPrice,
                    Isbn10: item.Isbn10,
                    Isbn13: item.Isbn13,
                    buyBoxNew: item.buyBoxNew,
                }
                console.log(datam)

                $.ajax({
                    type: 'post',
                    url: ApiUrl + 'ExtensionWebServis/ajaxCall',
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
                    },
                    cache: false,
                    dataType: 'json',
                    timeout: 500000,
                    data: datam,
                    success: function (cevap) {
                        console.log(cevap)
                        if (cevap.hata) {
                            console.log('Hata')
                        } else {
                            if (cevap.result) {
                                console.log('Sipariş listesi başarıyla alındı! UrunListeleriniGonder()')
                                // fiyatkontroldeki veriler duruma göre silinecek. lcaol storage sync
                                var gelenJson = cevap.result
                                console.log(gelenJson)
                                if (gelenJson['1'] != null && gelenJson['1'] != undefined) {
                                    console.log('Sipariş Alınacak')
                                    console.log(gelenJson[0])
                                    console.log(gelenJson[1])
                                    var SiparisListesiLastIndex = parseInt(gelenJson['1'].length) - 1
                                    var SiparisIndex = 0
                                    chrome.storage.sync.set(
                                        {
                                            Durum: 'UrunAl',
                                            AdresEklendi: false,
                                        },
                                        function () {
                                            chrome.storage.local.set(
                                                {
                                                    AdresBilgileri: gelenJson[0],
                                                    SiparisBilgileri: gelenJson[1],
                                                    SiparisListesiLastIndex: SiparisListesiLastIndex,
                                                    SiparisIndex: SiparisIndex,
                                                },
                                                function () {
                                                    console.log('Siparişler alınacak. ')
                                                    UrunAl(0)
                                                }
                                            )
                                        }
                                    )
                                } else {
                                    //localstorage'ları temizle

                                    setTimeout(function () {
                                        console.log('Yeni Ürüne Geçilecek! UrunListeleriniGonder()')
                                        UrunGetir()
                                    }, 2000)
                                }
                            }
                        }
                        console.log('Gönderildi')
                    },
                    error: function (req, textStatus, errorThrown) {
                        console.log('Ooops, something happened: ' + textStatus + ' ' + errorThrown)
                    },
                })
            }
        )
    } else {
        SekmeKapat(1)
    }
}

function UrunZararYaz(fiyat = 0) {
    chrome.storage.sync.get(['UrunID', 'ApiUrl'], function (item) {
        console.log('İstenilen ürüne  uygun fiyat ve diğer şartlar sağlanamadı!')
        var stringArray = []
        $.ajax({
            type: 'post',
            url: item.ApiUrl + 'ExtensionWebServis/ajaxCall',
            beforeSend: function (xhr) {
                xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
            },
            cache: false,
            dataType: 'json',
            data: {
                ID: item.UrunID,
                price: fiyat,
                orderArray: stringArray,
                tip: 'newOrderFiltre',
            },
            success: function (cevap) {
                console.log(cevap)
                if (cevap.hata) {
                    console.log('Hata')
                } else {
                    if (cevap.result == null || cevap.result.length == 0) {
                        console.log(cevap.result)
                        console.log('UrunZararYaz(' + fiyat + ')  ç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', 'AbeUrl', 'ISBN'],
        function (item) {
            var link = ''
            var isbn = item.ISBN
            var SiparisBilgileri = item.SiparisBilgileri
            var SiparisIndex = item.SiparisIndex
            var SiparisListesiLastIndex = item.SiparisListesiLastIndex - tekrar
            console.log(SiparisListesiLastIndex)
            console.log(SiparisIndex)
            console.log(host)
            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)
                    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.thriftbooks.com') {
                    SekmeKapat(1)
                }
            } else {
                console.log('Sipariş Listesinde Uygun Sipariş Kalmadı!')
                UrunZararYaz()
            }
        }
    )
}

function AmzUrunAl(IstenilenFiyat) {
    var Condition = QueryStringOku('condition')

    setTimeout(function () {
        if (Condition == 'new') {
            if (
                document.querySelector(
                    '#tmmSwatches > ul > li.swatchElement.selected > span > span:nth-child(3) > span.olp-new.olp-link > span > a'
                )
            )
                document
                    .querySelector(
                        '#tmmSwatches > ul > li.swatchElement.selected > span > span:nth-child(3) > span.olp-new.olp-link > span > a'
                    )
                    .click()
            else if (
                document.querySelector(
                    '#mediaOlp > div > div > div > div.a-fixed-right-grid-col.accordion-row-left-content.a-col-left > div:nth-child(2) > span > a'
                )
            ) {
                $(
                    '#mediaOlp > div > div > div > div.a-fixed-right-grid-col.accordion-row-left-content.a-col-left > div:nth-child(2) > span > a'
                ).each(function () {
                    console.log($(this).attr('href').indexOf('condition=new'))
                    if ($(this).attr('href').indexOf('condition=new') >= 0) {
                        $(this).click()
                    }
                })
            } else {
                //UrunZararYaz();
                return
            }
        } else {
            if (
                document.querySelector(
                    '#tmmSwatches > ul > li.swatchElement.selected > span > span:nth-child(3) > span.olp-used.olp-link > span > a'
                )
            )
                document
                    .querySelector(
                        '#tmmSwatches > ul > li.swatchElement.selected > span > span:nth-child(3) > span.olp-used.olp-link > span > a'
                    )
                    .click()
            else if (
                document.querySelector(
                    '#mediaOlp > div > div > div > div.a-fixed-right-grid-col.accordion-row-left-content.a-col-left > div:nth-child(2) > span:nth-child(3) > a'
                )
            ) {
                document
                    .querySelector(
                        '#mediaOlp > div > div > div > div.a-fixed-right-grid-col.accordion-row-left-content.a-col-left > div:nth-child(2) > span:nth-child(3) > a'
                    )
                    .click()
                // $("#mediaOlp div.a-fixed-right-grid-col.accordion-row-left-content.a-col-left  div:nth-child(2) span a").each(function(){
                // console.log($(this).attr('href').indexOf("condition=used"))
                // if($(this).attr('href').indexOf("condition=used") >= 0) {
                // $(this).click();
                // }

                // });
            } else {
                //UrunZararYaz();
                return
            }
        }
    }, 1000)

    waitForElement('#aod-container', function () {
        setTimeout(function () {
            if (Condition != 'new') {
                console.log(Condition)
                if (document.querySelector('#usedGood > div > label > input[type=checkbox]').checked)
                    document.querySelector('#usedGood').click()
                if (document.querySelector('#usedVeryGood > div > label > input[type=checkbox]').checked)
                    document.querySelector('#usedVeryGood').click()
                if (document.querySelector('#usedAcceptable > div > label > input[type=checkbox]').checked)
                    document.querySelector('#usedAcceptable').click()
                if (document.querySelector('#usedLikeNew > div > label > input[type=checkbox]').checked)
                    document.querySelector('#usedLikeNew').click()

                if (!document.querySelector('#' + Condition + ' > div > label > input[type=checkbox]').checked)
                    document.querySelector('#' + Condition).click()
            }
        }, 5000)
        setTimeout(function () {
            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 Price = 0
                var Seller = null

                var LocaldekiUrun = AmzUrunList.find((item) => item.index == itemIndex && item.Page == itemPage)
                var AmzSeller = LocaldekiUrun.Seller
                if (itemIndex == '-1') {
                    var Urun = $('#aod-pinned-offer')
                    var UrunFiyat = $('#aod-pinned-offer').find('.a-offscreen').text().trim().substr(1).replace(',', '')
                    if (document.querySelector('#pinned-offer-top-id > div:nth-child(3) > span > span'))
                        var KargoFiyat = document
                            .querySelector('#pinned-offer-top-id > div:nth-child(3) > span > span')
                            .textContent.split(' ')
                    else var KargoFiyat = 0
                    console.log(KargoFiyat.length)
                    if (KargoFiyat.length > 1) KargoFiyat = KargoFiyat[1].trim().substr(1).replace(',', '')
                    console.log(KargoFiyat)
                    var DUrunFiyat = parseFloat(UrunFiyat)
                    var DKargoFiyat = KargoFiyat.length > 1 ? parseFloat(KargoFiyat.replace(',', '')) : 0
                    Price = DUrunFiyat + DKargoFiyat
                    var Condition = $('#aod-pinned-offer')
                        .find('#aod-offer-heading > h5')
                        .text()
                        .replace(/\s/g, '')
                        .trim()
                    var Delivery = $('#aod-pinned-offer')
                        .find('#aod-fasttrack-1 #delivery-message > b')
                        .text()
                        .split('\n')
                        .map((item) => item.trim())
                        .join(' ')
                        .trim()
                    var isPrime = $('#aod-pinned-offer')
                        .find('#aod-offer-shipsFrom > div > div > div.a-fixed-left-grid-col.a-col-right > span')
                        .text()
                    if (isPrime == 'Amazon.com') var isPrime = isPrime == 'Amazon.com' ? true : false
                    Seller = $('#aod-pinned-offer')
                        .find('#aod-offer-soldBy > div > div > div.a-fixed-left-grid-col.a-col-right > a')
                        .text()
                        .trim()
                    var Positive = $('#aod-pinned-offer')
                        .find('#seller-rating-count-\\{iter\\} > span')
                        .text()
                        .split('%')
                    if (Positive.length > 0) Positive = Positive[0].split(')')[1]
                    var r = $('#aod-pinned-offer').find('#seller-rating-count-\\{iter\\} > span').text().split('%')
                    if (r.length > 0) r = r[0].split(')')[0].split(' ')[0].split('(')[1]
                    var Ratings = r != undefined ? r : '0'
                    Price = Price.toFixed(2)
                    //if (isPrime && Seller == '') Seller = 'Amazon.com'
                } else {
                    console.log(itemIndex)
                    var Urun = $('#aod-offer-list #aod-offer').eq(itemIndex) //document.querySelectorAll("#aod-offer")[itemIndex];
                    var UrunFiyat = Urun.find('.a-offscreen').text().trim().substr(1).replace(',', '')
                    var KargoFiyat = Urun.find(
                        '#aod-offer-price > div > div > div.a-fixed-left-grid-col.a-col-right > div > div > div.a-fixed-right-grid-col.aod-padding-right-10.a-col-left > span > span'
                    )
                        .text()
                        .split(' ')
                    if (KargoFiyat.length > 1) KargoFiyat = KargoFiyat[1].trim().substr(1).replace(',', '')
                    var DUrunFiyat = parseFloat(UrunFiyat)
                    var DKargoFiyat = KargoFiyat.length > 1 ? parseFloat(KargoFiyat.replace(',', '')) : 0
                    Price = DUrunFiyat + DKargoFiyat

                    var Condition = Urun.find('#aod-offer-heading > h5').text().replace(/\s/g, '').trim()
                    var Delivery = Urun.find('#delivery-message > b')
                        .text()
                        .split('\n')
                        .map((item) => item.trim())
                        .join(' ')
                        .trim()
                    var isPrime = Urun.find(
                        '#aod-offer-shipsFrom > div > div > div.a-fixed-left-grid-col.a-col-right > span'
                    ).text()
                    if (isPrime == 'Amazon.com') isPrime = true
                    else isPrime = false
                    Seller = Urun.find(
                        '#aod-offer-shipsFrom > div > div > div.a-fixed-left-grid-col.a-col-right > span'
                    )
                        .text()
                        .trim()
                    var Positive = Urun.find('#seller-rating-count-\\{iter\\} > span').text().split('%')
                    if (Positive.length > 0) Positive = Positive[0].split(')')[1]
                    var r = Urun.find('#seller-rating-count-\\{iter\\} > span').text().split('%')
                    if (r.length > 0) r = r[0].split(')')[0].split(' ')[0].split('(')[1]
                    var Ratings = r != undefined ? r : '-'
                    Price = Price.toFixed(2)
                }
                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)')
                    console.log(Urun)

                    var link = window.location.href

                    Urun.find("input[name='submit.addToCart']").click()

                    //Urun.find(".a-button-input").trigger("click");
                    setTimeout(function () {
                        chrome.storage.sync.set(
                            {
                                AmzSepetUrunLink: link,
                                AmzSeller: AmzSeller,
                                NextPrice: NPrice,
                            },
                            function () {
                                window.location.href = 'https://www.amazon.com/gp/cart/view.html?PgNm=Amz&Basket=True'
                            }
                        )
                    }, 10000)
                } else {
                    console.log('İki ürün aynı değil listedeki diğer ürüne geçilecek! (Amazon)')
                    UrunZararYaz(Price)
                }
            })
        }, 10000)
    })
}

function AmzBasketPage() {
    console.log('AmzBasketPage()')

    var SepetCount = $('#nav-cart-count').text()
    console.log(SepetCount)
    if (SepetCount != undefined && SepetCount.length > 0) {
        if (parseInt(SepetCount) == 1) {
            console.log('Sepetteki ürün adeti: 1 Sipariş işlemleri devcam edecek! AmzBasketPage()')
            if (!$('#sc-buy-box-ptc-button')) window.location.reload

            $('#sc-buy-box-ptc-button').click()
            $('#sc-buy-box-ptc-button').trigger('click')
            $('#sc-buy-box-ptc-button > span').click()
            $('#sc-buy-box-ptc-button > span').trigger('click')
            $('#sc-buy-box-ptc-button > span > input').click()
            $('#sc-buy-box-ptc-button > span > input').trigger('click')

            console.log('proceedToCheckout tıklandı AmzBasketPage() ')
            var SepetKargoAdres =
                'https://www.amazon.com/gp/buy/addressselect/handlers/display.html?hasWorkingJavascript=1'
            // SekmeAc(SepetKargoAdres);
            // SekmeKapat(1);
        } else {
            if (parseInt(SepetCount) == 0)
                //UrunZararYaz();
                console.log(SepetCount + " Sepetteki ürün 1'den fazla sepet boşaltılacak!  AmzBasketPage() ")
            var amzlink = 'https://www.amazon.com/gp/cart/view.html?'
            var params = 'PgNm=Amz&Sil=True'
            var link = amzlink + params
            SayfaGit(link, 1)
        }
    } else {
        console.log('Sepet Boş! Ürün tekrar sepete atılacak. AmzBasketPage()')
        chrome.storage.sync.get(['AmzSepetUrunLink'], function (item) {
            console.log(item.AmzSepetUrunLink)
        })
    }
}

function AmzBasketBosalt() {
    console.log('AmzBasketBosalt()')
    var Listeler = []
    var liste1 = $('.sc-batch-items').children()
    var liste1Count = liste1.length
    Listeler.push({
        liste: '.sc-batch-items',
        count: liste1Count,
    })
    var liste2 = $('.sc-batches-list-body').children()
    var liste2Count = liste2.length
    Listeler.push({
        liste: '.sc-batches-list-body',
        count: liste2Count,
    })
    var liste3 = $('.sc-list-body').children()
    var liste3Count = liste3.length
    Listeler.push({
        liste: '.sc-list-body',
        count: liste3Count,
    })

    console.log(liste1Count)
    console.log(liste2Count)
    console.log(liste3Count)

    var HangiListe = Listeler.find((item) => item.count > 0)
    var AranacakListe = ''
    var AranacakCount = ''
    if (HangiListe != null && HangiListe != undefined) {
        AranacakListe = HangiListe.liste
        AranacakCount = HangiListe.count
    } else {
        AranacakListe = '.sc-batch-items'
        AranacakCount = '0'
    }

    var headerText = $('.sc-cart-header').text().trim()

    if (parseInt(AranacakCount) > 0 && headerText != 'Your Shopping Cart is empty.') {
        console.log("Sepetteki ürün 0'dan fazla AmzBasketBosalt()")

        $(AranacakListe)
            .children()
            .each(function (index) {
                $(this).find('.sc-action-delete > span > input').click()
                $(this).find('.sc-action-delete > span > input').trigger('click')
                $(this).find('.sc-action-delete > span').click()
                $(this).find('.sc-action-delete > span').trigger('click')

                AmzBasketBosalt2(index)
            })
    } else {
        console.log('Sepet Boş. Ürün sepete tekrar atılacak. AmzBasketBosalt()')
        chrome.storage.sync.get(['AmzSepetUrunLink'], function (item) {
            console.log(item.AmzSepetUrunLink)
            SayfaGit(item.AmzSepetUrunLink, 1)
        })
    }
}

function AmzBasketBosalt2(index) {
    setTimeout(function () {
        $('.sc-list-body').find('div').eq(index).find('.sc-action-delete > span > input').click()
        $('.sc-list-body').find('div').eq(index).find('.sc-action-delete > span > input').trigger('click')
        $('.sc-list-body').find('div').eq(index).find('.sc-action-delete > span').click()
        $('.sc-list-body').find('div').eq(index).find('.sc-action-delete > span').trigger('click')
        window.location.reload()
    }, 100 * parseInt(index))
}

function AmzItemNotAdded() {
    console.log('AmzItemNotAdded()')
    var SepetCount = $('#nav-cart-count').text()
    console.log(SepetCount)
    if (SepetCount != undefined && SepetCount.length > 0) {
        if (parseInt(SepetCount) == 1) {
            AmzBasketPage()
        }
    }
    var isNotAdded = $('#huc-v2-order-row-confirm-text').text().trim()

    var CartIsEmpty = ''
    if (document.querySelector('#sc-active-cart h1'))
        var CartIsEmpty = document.querySelector('#sc-active-cart h1').textContent.trim()
    if (document.querySelector('#activeCartViewForm > div > h2.a-spacing-mini.a-spacing-top-base.sc-empty-cart-header'))
        var CartIsEmpty = document
            .querySelector('#activeCartViewForm > div > h2.a-spacing-mini.a-spacing-top-base.sc-empty-cart-header')
            .textContent.trim()
    if (
        document.querySelector(
            '#sc-active-cart > div > div.a-column.a-span8.a-span-last > div.a-row.sc-your-amazon-cart-is-empty > h2'
        )
    )
        var CartIsEmpty = document
            .querySelector(
                '#sc-active-cart > div > div.a-column.a-span8.a-span-last > div.a-row.sc-your-amazon-cart-is-empty > h2'
            )
            .textContent.trim()
    console.log(CartIsEmpty)
    if (isNotAdded == 'Not added') {
        //birse git ikiyse sil?
        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 (CartIsEmpty === 'Your Amazon Cart is empty.') {
        var amzlink = 'https://www.amazon.com/gp/cart/view.html?'
        var params = 'PgNm=Amz&Sil=True'
        var link = amzlink + params
        console.log(link)
        SayfaGit(link, 1)
    } else if (CartIsEmpty == 'Your Amazon Cart is empty') {
        var amzlink = 'https://www.amazon.com/gp/cart/view.html?'
        var params = 'PgNm=Amz&Sil=True'
        var link = amzlink + params
        SayfaGit(link, 1)
    }
}

function AmzAdresEkle() {
    console.log('AmzAdresEkle()')
    chrome.storage.local.get(['AdresBilgileri'], function (item) {
        var data = item.AdresBilgileri
        $('#add-new-address-popover-link').parent().click()
        $('#add-new-address-popover-link').parent().trigger('click')
        //Rita Cabases Goni ||  430 Grand Bay Dr Apt 1406|| Key Biscayne|| FL ||33149
        if ($('input[name=address-ui-widgets-enterAddressFullName]').length > 0) {
            setTimeout(function () {
                $('input[name=address-ui-widgets-enterAddressFullName]').val(data.Name)
                $('input[name=address-ui-widgets-enterAddressLine1]').val(data.Adres1)
                $('input[name=address-ui-widgets-enterAddressLine2]').val(data.Adres2)
                $('input[name=address-ui-widgets-enterAddressCity]').val(data.City)
                $('input[name=address-ui-widgets-enterAddressStateOrRegion]').val(data.State)
                $('#address-ui-widgets-enterAddressStateOrRegion-dropdown-nativeId').val(data.State)
                $('input[name=address-ui-widgets-enterAddressPostalCode]').val(data.PKod)
                $('#enterAddressCountryCode').val(data.Country).prop('selected', true)
                $('input[name=address-ui-widgets-enterAddressPhoneNumber]').val(data.Phone)
                setTimeout(function () {
                    document.querySelector('#address-ui-widgets-form-submit-button > span > input').click()
                    document.querySelector('#address-ui-widgets-form-submit-button > span > input').click()
                }, 1000)
                $('#address-ui-checkout-submit-button').children().eq(0).find('input').click()
                $('#address-ui-checkout-submit-button').children().eq(0).find('input').trigger('click')
                OriginalAddressCheck()
            }, 1000)
        } else {
            setTimeout(function () {
                $('input[name=enterAddressFullName]').val(data.Name)
                $('input[name=enterAddressAddressLine1]').val(data.Adres1)
                $('input[name=enterAddressAddressLine2]').val(data.Adres2)
                $('input[name=enterAddressCity]').val(data.City)
                $('input[name=enterAddressStateOrRegion]').val(data.State)
                $('input[name=enterAddressPostalCode]').val(data.PKod)
                $('#enterAddressCountryCode').val(data.Country).prop('selected', true)
                $('input[name=enterAddressPhoneNumber]').val(data.Phone)
                setTimeout(function () {
                    document.querySelector('#address-ui-widgets-form-submit-button > span > input').click()
                    document.querySelector('#address-ui-widgets-form-submit-button > span > input').click()
                }, 1000)
                $('.a-popover-footer > div').children().eq(0).find('input').click()
                $('.a-popover-footer > div').children().eq(0).find('input').trigger('click')
                OriginalAddressCheck()
            }, 1000)
        }
    })
}

function OriginalAddressCheck() {
    setTimeout(function () {
        if ($('#a-popover-content-1').parent().parent().parent().css('visibility') == 'visible') {
            //$(".radio-option-list").children().eq(0).find('input:radio[name=addr]').prop('checked', true);
            if (document.getElementById('address-ui-widgets-original-address-block_id-input'))
                document.getElementById('address-ui-widgets-original-address-block_id-input').checked = true
            if (document.querySelector('input[aria-labelledby=address-ui-widgets-form-submit-button-announce]'))
                document.querySelector('input[aria-labelledby=address-ui-widgets-form-submit-button-announce]').click()

            $('#a-popover-content-1').next('.checkout-footer').addClass('Butonlar')
            // $(".Butonlar > div").children().eq(0).click();
            // $(".Butonlar > div").children().eq(0).trigger("click");
            // $(".Butonlar > div").children().eq(0).find("input").trigger("click");
            // $(".Butonlar > div").children().eq(0).find("input").css("margin-left", "50px;");
            // $(".Butonlar > div").children().eq(0).find("input").click();
            // $(".Butonlar > div").children().eq(0).find("input").trigger("click");
            // $(".Butonlar > div").children().eq(0).find("input").next("span").click();
            // $(".Butonlar > div").children().eq(0).find("input").next("span").trigger("click");

            var AdresError = 'Please correct the fields marked in red'
            var ErrorText = $('.a-alert-error').text()
            var AdresErrorDurum = ErrorText.indexOf(AdresError) !== -1
            if (AdresErrorDurum) {
                console.log('Please correct the fields marked in red || Çıktı... Yeni ürün getirilecek!')
                $('input[type=submit][aria-labelledby=address-ui-checkout-submit-button-announce]').click()
                $('input[type=submit][aria-labelledby=address-ui-checkout-submit-button-announce]').trigger('click')
                AmzOrderComplete()
                //UrunZararYaz();
            } else {
                OriginalAddressCheckButtonClick()
                console.log('Adres düzeltme önerildi: Original adres seçildi.')
            }
        } else {
            var AdresError = 'Please correct the fields marked in red'
            var ErrorText = $('.a-alert-error').text()
            var AdresErrorDurum = ErrorText.indexOf(AdresError) !== -1
            if (AdresErrorDurum) {
                console.log('Please correct the fields marked in red || Çıktı... Yeni ürün getirilecek!')
                $('input[type=submit][aria-labelledby=address-ui-checkout-submit-button-announce]').click()
                $('input[type=submit][aria-labelledby=address-ui-checkout-submit-button-announce]').trigger('click')
                // $("input[type=submit][aria-labelledby=newAddressUseThisAddressButton-announce]").click();
                // $("input[type=submit][aria-labelledby=newAddressUseThisAddressButton-announce]").trigger('click');
                AmzOrderComplete()
                //UrunZararYaz();
            } else {
                AmzOrderComplete()
                console.log('Adres düzeltme önerilmedi!')
            }
        }
    }, 1000)
}

function OriginalAddressCheckButtonClick() {
    setTimeout(function () {
        if (document.getElementById('address-ui-widgets-original-address-block_id-input'))
            document.getElementById('address-ui-widgets-original-address-block_id-input').checked = true
        if (document.querySelector('input[aria-labelledby=address-ui-widgets-form-submit-button-announce]'))
            document.querySelector('input[aria-labelledby=address-ui-widgets-form-submit-button-announce]').click()
        document.querySelector('#address-ui-widgets-enterAddressFormContainer > span > span > span > input').click()
        //$("input[type=submit][value=SAVE_ADDRESS]").click();
        // $("input[type=submit][value=SAVE_ADDRESS]").trigger('click');
        // $(".Butonlar > div").children().eq(0).click();
        // $(".Butonlar > div").children().eq(0).trigger("click");
        // $(".Butonlar > div").children().eq(0).find("input").trigger("click");
        // $(".Butonlar > div").children().eq(0).find("input").click();
        // $(".Butonlar > div").children().eq(0).find("input").trigger("click");
        // $(".Butonlar > div").children().eq(0).find("input").next("span").click();
        // $(".Butonlar > div").children().eq(0).find("input").next("span").trigger("click");
        AmzOrderComplete()
    }, 1000)
}

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 () {
            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(10);
            }
            if (i == 5 || i == 15 || i == 25) {
                $('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')
                if (document.querySelector('#placeYourOrder > span > input')) {
                    document.querySelector('#placeYourOrder > span > input').click()
                } else {
                    document.querySelector('#submitOrderButtonId > span > input').click()
                }
            }
        }, 3000)
        setTimeout(function () {
            waitForElement('#subtotals-marketplace-table > tbody > tr > td.grand-total-price', function () {
                var LastPrice = $('#subtotals-marketplace-table > tbody > tr > td.grand-total-price')
                    .text()
                    .trim()
                    .split('$')['1']
                var DLastPrice = parseFloat(LastPrice)
                var DUrunFiyat = parseFloat(item.UrunFiyat)
                var DNextPrice = parseFloat(item.NextPrice)
                DUrunFiyat = DUrunFiyat //+ (DUrunFiyat * 10 / 100);
                console.log(DLastPrice)
                console.log(DUrunFiyat)
                console.log(DNextPrice)

                if (DLastPrice <= DUrunFiyat || DLastPrice <= DNextPrice) {
                    chrome.storage.sync.set(
                        {
                            Durum: 'SiparisTamamla',
                            DLastPrice: DLastPrice,
                            OrderItemCount: 1,
                        },
                        function () {
                            // $("#submitOrderButtonId > span > input").addClass("tikladim1");
                            // $("#submitOrderButtonId > span > input").click();
                            // $("#submitOrderButtonId > span > input").trigger("click");

                            waitForElement('#placeYourOrder > span > input', 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++
                    UrunZararYaz(DLastPrice)
                }
            })
        }, 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('4147400302209257')
                $("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('purchaseId')
            SayfaGit('https://www.amazon.com/gp/css/order-history', 1)
            SiparisTamamla(MagazaAdi, SiparisNo, AbeOrAmazon)
            console.log(
                'MagazaAdi:' +
                    MagazaAdi +
                    ' SiparisNo:' +
                    SiparisNo +
                    ' AbeSaticiNo: ' +
                    '-' +
                    'Son Fiyat:' +
                    item.DLastPrice
            )
        }
    })

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

function AmzOrderInfoGet() {
    waitForElement('#orderIdField > span > div', function () {
        chrome.storage.sync.get(['OrderItemCount'], function (item) {
            count = 0
            orderArray = []
            $('.order-card').each(function () {
                console.log($(this))
                if (count < item.OrderItemCount) {
                    var price = $(this)
                        .find('div.a-column.a-span2.yohtmlc-order-total > div.a-row.a-size-base > span.value')
                        .text()
                    var orderId = $(this)
                        .find('div.a-row.a-size-mini.yohtmlc-order-id > span.a-color-secondary.value > bdi')
                        .text()
                    var trackingUrl = $(this).find('.shipment .actions a').attr('href')
                    var isbn = $(this)
                        .find(
                            'div.a-box.shipment div.a-fixed-right-grid.a-spacing-top-medium  div.a-fixed-right-grid-col.a-col-left div.a-text-center.a-fixed-left-grid-col.a-col-left a'
                        )
                        .attr('href')
                        .split('/')[3]
                    orderArray[count] = []
                    orderArray[count]['price'] = price.trim().split('$')[1]
                    orderArray[count]['orderId'] = orderId
                    orderArray[count]['trackingUrl'] = trackingUrl
                    orderArray[count]['isbn'] = isbn
                    count++
                }
            })
            $('#orderCard').each(function () {
                console.log($(this))
                if (count < item.OrderItemCount) {
                    var price = $(this)
                        .find('#orderCardHeader > div > div > div:nth-child(2) > div.a-row.a-size-base')
                        .text()
                        .trim()
                        .split('$')[1]
                    console.log($(this).find('#orderIdField > span > div').text())
                    var orderId = $(this).find('#orderIdField > span > div').text().trim().split('\n')[2].trim()
                    var trackingUrl = $(this)
                        .find(
                            '#orderCardDeliveryBox > div > div.a-row.a-spacing-top-medium > div.a-column.a-span3.a-span-last > div > span:nth-child(2) > span > a'
                        )
                        .attr('href')
                    var isbn = $(this)
                        .find('#itemDetail > div.a-column.a-span2.imageContainer > a')
                        .attr('href')
                        .split('/')[3]
                    if (isbn == undefined) {
                        isbn = $(this)
                            .find('#itemDetail > div.a-column.a-span2.imageContainer > a')
                            .attr('href')
                            .split('/')[2]

                        isbn = isbn.split('?')[0]
                    }
                    orderArray[count] = []
                    orderArray[count]['price'] = parseFloat(price)
                    orderArray[count]['orderId'] = orderId
                    orderArray[count]['trackingUrl'] = trackingUrl
                    orderArray[count]['isbn'] = isbn
                    count++
                }
            })
            console.table(orderArray)
            chrome.storage.sync.get(['AmzSeller', 'DLastPrice'], function (item) {
                var MagazaAdi = item.AmzSeller
                var AbeOrAmazon = 0
                var SiparisNo = orderArray[0]['orderId']
                SiparisTamamla(MagazaAdi, SiparisNo, AbeOrAmazon, orderArray)
            })
        })
    })
}

function SiparisTamamla(MagazaAdi, SiparisNo, AbeOrAmazon, orderArray) {
    chrome.storage.sync.get(['UrunID', 'PcName', 'DLastPrice', 'UrunFiyat', 'ApiUrl', 'MagazaAdi'], function (item) {
        PcName = item.PcName
        //MTip: Mağaza Tip (Amazon (0), Abe (1))
        var AbeSaticiNo = '-'
        if (AbeOrAmazon == '0') {
            AbeSaticiNo = '-'
        }
        if (MagazaAdi == '') MagazaAdi = 'ThriftBooks'
        var datam = {
            ID: item.UrunID,
            tip: 'newOrderEnd',
            MAd: MagazaAdi,
            magazaDeger: item.MagazaAdi,
            SipNo: SiparisNo,
            MTip: AbeOrAmazon,
            SNo: AbeSaticiNo,
            PCAd: PcName,
            Price: item.DLastPrice,
            OurPrice: item.UrunFiyat,
            TrackingUrl: orderArray[0]['trackingUrl'],
            Isbn: orderArray[0]['isbn'],
            manuelasin: orderArray[0]['isbn'],
        }
        console.log(datam)
        $.ajax({
            type: 'post',
            url: item.ApiUrl + 'ExtensionWebServis/ajaxCall',
            beforeSend: function (xhr) {
                xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
            },
            cache: false,
            dataType: 'json',
            data: datam,
            timeout: 500000,
            success: function (cevap) {
                console.log(cevap)
                if (cevap.hata == '0') {
                    console.log('Hata: Sipariş Bilgileri Gönderilemedi!')

                    //Hata alındı bilgilendirilme yapılacak
                } else {
                    if (cevap.result == '1') {
                        console.log(cevap.result)
                        console.log('Sipariş bilgileri gönderildi')
                        setTimeout(function () {
                            UrunGetir()
                        }, 2000)
                    } else {
                    }
                }
                console.log('Sipariş Tamamla Response!')
            },
            error: function (req, textStatus, errorThrown) {
                console.log('Ooops, something happened: ' + textStatus + ' ' + errorThrown)
            },
        })
    })
}

function AbeUrunAl(IstenilenFiyat) {
    if ($('.AddToCartButton-Desktop button')) {
        $('.AddToCartButton-Desktop button').click()
        SayfaGit('https://www.thriftbooks.com/shopping-cart/?PgNm=Abe&Basket=True', 2)
    } else SayfaGit('https://www.thriftbooks.com/shopping-cart/?PgNm=Abe&Basket=True', 2)

    // chrome.storage.local.get(["AbeUrunList"], function (item) {
    // console.log(item.AbeUrunList);
    // var AbeUrunList = item.AbeUrunList;
    // var itemIndex = QueryStringOku("itemIndex");
    // var itemPage = QueryStringOku("itemPage");
    // var NPrice = QueryStringOku("NPrice");
    // var LocaldekiUrun = AbeUrunList.find(item => item.index == itemIndex && item.Page == itemPage);

    // var Urun = $(".result-set").find("div.result").eq(itemIndex);
    // var UrunFiyat = Urun.find(".srp-item-price").text().split(" ")[1];
    // var KargoFiyat = Urun.find(".srp-item-price-shipping").text().split(" ")[1];

    // var DUrunFiyat = parseFloat(UrunFiyat);
    // var DKargoFiyat = KargoFiyat != undefined ? parseFloat(KargoFiyat) : 0;
    // var Price = DUrunFiyat + DKargoFiyat;

    // var c = Urun.find(".clear-all").children().eq(1).text().split("Condition:")[1];
    // var Condition = c != undefined ? c.split(".")[0].trim() : "-";
    // var Seller = Urun.find(".bookseller-info").children().eq(0).children().text().trim();

    // Price = Price.toFixed(2);

    // 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ı işlemlere devam edilecek! (Abebook)");

    // var a = Urun.find(".btn-add-to-basket").attr('href');

    // var abelink = "https://www.thriftbooks.com/" + a;
    // var params = "&PgNm=Abe&Basket=True";
    // var link = abelink + params;

    // chrome.storage.sync.set({
    // 'AbeSepetUrunLink': link,
    // "NextPrice": NPrice
    // }, function () {
    // SayfaGit(link, 1);

    // });

    // } else {

    // console.log("İki ürün aynı değil, diğer ürüne geç! (Abebook)");
    // UrunAl(0);

    // }

    // });
}

function AbeBasketPage() {
    console.log('AbeBasketPage()')

    var SepetCount = $('.is-desktop .GlobalCart-count').text()

    if (SepetCount != undefined && SepetCount.length > 0) {
        var sptCount = parseInt(SepetCount)
        if (parseInt(SepetCount) > 1) {
            console.log('Sepetteki ürün 1 dan fazla')
            window.location.href = 'https://www.thriftbooks.com/shopping-cart/'
            // jQuery(function($) { // this does the trick and also makes sure jQuery is not conflicting with another library
            // setTimeout(function () {
            // document.querySelector('div.ShoppingCartItem-controls > a.ShoppingCartItem-remove').click();
            // location.reload();
            // }, 3000);
            // });
        } else {
            // console.log("Sepetteki ürün adeti 1. İşlemlere devam edilecek. AbeBasketPage()");
            // var ErrorMessage = $(".errorMessage").text();
            // var itemSold = "Item sold";
            // var itemSoldDurum = ErrorMessage.indexOf(itemSold) !== -1;
            // var itemSoldText = $(".status > .alert").text();
            // if (itemSoldDurum ) { //|| itemSoldText.length > 0 && itemSoldText == "Item already in Basket"
            //console.log("Sepetteki ürün adeti 1. Fakat ürün satılmış. Yeni Ürüne geçilecek! AbeBasketPage()");
            // UrunZararYaz();
            //UrunAl(1);
            // } else {
            // console.log("Sepetteki ürün adeti 1. Ürün stokta mevcut! AbeBasketPage()");
            var SepetKargoAdres = 'https://www.thriftbooks.com/checkout/shipping/?AddAdres=true&PgNm=Abe'
            SayfaGit(SepetKargoAdres, 1)

            // }
        }
    } else {
        var ErrorMessage = $('.errorMessage').text()
        var itemSold = 'Item sold'
        var itemSoldDurum = ErrorMessage.indexOf(itemSold) !== -1
        if (itemSoldDurum) {
            console.log('ürün satılmış. Yeni Ürüne geçilecek! AbeBasketPage()')
            // UrunZararYaz();
            UrunAl(0)
        } else {
            console.log('Sepet Boş. Ürün tekrar alınacak! AbeBasketPage()')
            chrome.storage.sync.get(['AbeSepetUrunLink'], function (item) {
                console.log(item.AbeSepetUrunLink)
            })
        }
    }
}

function AbeBasketBosalt() {
    console.log('AbeBasketBosalt()')

    var SepetCount = $('.is-desktop .GlobalCart-count').text()
    if (SepetCount != undefined && SepetCount.length > 0) {
        if (parseInt(SepetCount) != 0) {
            console.log("Sepetteki ürün 0'dan fazla. Sepet boşaltılacak! AbeBasketBosalt()")
            jQuery(function ($) {
                // this does the trick and also makes sure jQuery is not conflicting with another library
                setTimeout(function () {
                    document.querySelector('div.ShoppingCartItem-controls > a.ShoppingCartItem-remove').click()
                }, 3000)
                setTimeout(function () {
                    location.reload()
                }, 5000)
            })
        } else {
            console.log('Sepetteki ürün 0 (Code:1)')
            UrunAl(1)
            SekmeKapat(1)
        }
    } else {
        if ($('.saveDelete').length > 0) {
            $('.saveDelete').find('.secondarybutton').click()
            $('.saveDelete').find('.secondarybutton').trigger('click')
        } else {
            console.log('Sepet Boş. Ürün tekrar alınacak. AbeBasketBosalt()')
            chrome.storage.sync.get(['AbeSepetUrunLink'], function (item) {
                console.log(item.AbeSepetUrunLink)
                SayfaGit(item.AbeSepetUrunLink, 1)
            })
        }
    }
}
function AbeAdresSilme() {
    console.log($('#delete-address-link-10'))
    if ($('#delete-address-link-10').length) {
        setTimeout(function () {
            $('#delete-address-link-10').click()
            $('#delete-address-link-10').trigger('click')
        }, 5000)
        var url = 'https://www.abebooks.com/servlet/ShippingAddress?AddAdres=true&PgNm=Abe'
        getSayfa(url)
    } else {
        AbeAdresEkle()
    }
}
function AbeAdresEkle() {
    console.log('AbeAdresEkle()')
    chrome.storage.local.get(['AdresBilgileri'], function (item) {
        if ($('.Shipping-SavedAddressCol')) {
            setTimeout(function () {
                $('.Button').click()
                $('.Button').trigger('click')
            }, 3000)
        } else {
            chrome.storage.sync.set(
                {
                    AdresEklendi: true,
                },
                function () {
                    var data = item.AdresBilgileri
                    setTimeout(function () {
                        var firstName = document.querySelector('#FirstName') //$("#FirstName");
                        $('#FirstName').val(data.Name.split(' ')[0])
                        firstName.setAttribute('value', data.Name.split(' ')[0])
                        firstName.dispatchEvent(new Event('change', { bubbles: true }))
                        firstName.dispatchEvent(new Event('blur', { bubbles: true }))

                        var lastName = document.querySelector('#LastName')
                        $('#LastName').val(data.Name.split(' ')[1])
                        lastName.setAttribute('value', data.Name.split(' ')[1])
                        lastName.dispatchEvent(new Event('change', { bubbles: true }))
                        lastName.dispatchEvent(new Event('blur', { bubbles: true }))

                        var address1 = document.querySelector('#AddressLine1')
                        $('#AddressLine1').val(data.Adres1)
                        address1.setAttribute('value', data.Adres1)
                        address1.dispatchEvent(new Event('change', { bubbles: true }))
                        address1.dispatchEvent(new Event('blur', { bubbles: true }))

                        var city = document.querySelector('#City')
                        $('#City').val(data.City)
                        city.setAttribute('value', data.City)
                        city.dispatchEvent(new Event('change', { bubbles: true }))
                        city.dispatchEvent(new Event('blur', { bubbles: true }))

                        var country = document.querySelector('#Country')
                        $('#Country').val(17).prop('selected', true)
                        country.options[1].selected = true
                        country.dispatchEvent(new Event('change', { bubbles: true }))
                        country.dispatchEvent(new Event('blur', { bubbles: true }))

                        var state = document.querySelector('#State')
                        $('#State').val(data.State)
                        state.setAttribute('value', data.State)
                        state.dispatchEvent(new Event('change', { bubbles: true }))
                        state.dispatchEvent(new Event('blur', { bubbles: true }))

                        var pKod = document.querySelector('#PostalCode')
                        $('#PostalCode').val(data.PKod)
                        pKod.setAttribute('value', data.PKod)
                        pKod.dispatchEvent(new Event('change', { bubbles: true }))
                        pKod.dispatchEvent(new Event('blur', { bubbles: true }))

                        var Phone = document.querySelector('#PhoneNumber')
                        $('#PhoneNumber').val(data.Phone)
                        Phone.setAttribute('value', data.Phone)
                        Phone.dispatchEvent(new Event('change', { bubbles: true }))
                        Phone.dispatchEvent(new Event('blur', { bubbles: true }))
                    }, 1000)
                    setTimeout(function () {
                        $('.Button').click()
                        $('.Button').trigger('click')
                    }, 5000)
                }
            )
        }
    })
}

function AbeEditBilling() {
    console.log('AbeEditBilling();')
    chrome.storage.sync.get(['UrunID', 'UrunFiyat', 'NextPrice'], function (item) {
        waitForElement('.price-muted', function () {
            var LastPrice = $('div.medium.price-muted.mt-lg.mb-lg > div.pull-right').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) {
                var adres = $('#addressid').parent('td').text().length
                console.log('fatura adresi eklenecek')
                if (adres > 100) {
                    console.log('AbeEditBilling Button tıklanacak!')
                    $('#editbillinginfo').click()
                    $('#editbillinginfo').trigger('click')
                }
            } else {
                console.log('AbeEditBilling() son fiyat ile istenilen fiyattan fazla!')
                UrunAl(0)
            }
        })
    })
}

function AbeSaveBilling() {
    console.log('AbeSaveBilling()')

    // $('iframe').load(function(){
    // $('iframe').contents().find('input#cvv').focus();
    // $('iframe').contents().find('input#cvv').valueOf($(this).val(421));
    // });

    $('.Button').click()
    $('.Button').trigger('click')
    if ($('#cvv')) {
        $('#cvv').val(421)
        // $(".Button").click();
        // $(".Button").trigger("click");
    } else {
        $('.Button').click()
        $('.Button').trigger('click')
    }
}

function AbeOrderComplete() {
    console.log('AbeOrderComplete();')
    //$(".col-sm-5 .small-plus").addClass("shippinge");
    chrome.storage.sync.get(['UrunID', 'UrunFiyat', 'NextPrice'], function (item) {
        //waitForElement(".price-muted", function () {
        var LastPrice = $('.OrderSummary-Total > div.OrderSummary-ItemPad').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) {
            console.log('AbeOrderComplete Button tıklanacak!')

            //var kargoadres = $(".shippinge").text().length;
            // var faturaadres = $(".optimizely-billing-address").text().length;

            //console.log(faturaadres);
            //console.log("tıklanacak");

            //if (kargoadres > 100 && faturaadres > 100) {
            chrome.storage.sync.set(
                {
                    Durum: 'SiparisTamamla',
                    DLastPrice: DLastPrice,
                    AdresEklendi: false,
                },
                function () {
                    //tah
                    $('.Button').click()
                    $('.Button').trigger('click')
                    console.log('abe Button tıklanacak')
                }
            )
            //}
        } else {
            console.log('AbeOrderComplete() son fiyat ile istenilen fiyattan fazla!')

            UrunAl(0)
        }
        //});
    })
}

function AbeSiparisTamamla() {
    console.log('AbeSiparisTamamla()')

    setTimeout(function () {
        var MagazaAdi = 'ThriftBooks'
        var SiparisNo = $('.OrderFinal-OrderNumber').text().split('#')[1].split(')')[0]
        console.log(SiparisNo + ' ' + MagazaAdi)
        var AbeOrAmazon = 1
        var AbeSaticiNo = '0' //$("a[href*='/servlet/BuyerOrderTrackPL']").text().split(':')[1];//form.find(".bookseller-heading").find(".po-number").text().trim().split(":")["1"].trim();
        console.log('MagazaAdi:' + MagazaAdi + ' SiparisNo:' + SiparisNo + ' AbeSaticiNo: ' + AbeSaticiNo)
        console.log(AbeSaticiNo)
        SiparisTamamla(MagazaAdi, SiparisNo, AbeOrAmazon, AbeSaticiNo)
    }, 1000)
}

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 () {})
}

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,
        })
    }, 200)
}
