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

var kontrol

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

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

var linkKontrolCount = 0
var urunKontrolCount = 0

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

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

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

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

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

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

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

        var datam = {
            setdata: '1',
            dataArray: dataArray,
            extensionName: item.PcName
        }
        console.log(dataArray.length);
        if(dataArray.length === 0) {
            chrome.storage.local.set(
                {
                    KontrolUrl1: 'Hardcover',
                    KontrolUrl2: 'Hardcover',
                },
                function () {
                    //console.log("Birinci url kontrol edildi: " + deger);
                    SekmeKapat(1)
                }
            )
        } else {
        console.log(datam)
        $.ajax({
            type: 'post',
            url: item.ApiUrl + '/api/setProductData',
            beforeSend: function (xhr) {
                xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
            },
            cache: false,
            dataType: 'json',
            data: datam,
            success: function (cevap) {
                console.log(cevap)
                if (cevap.hata == '0') {
                    console.log('Hata: Sipariş Bilgileri Gönderilemedi!')
                    SekmeKapat(2)
                    //Hata alındı bilgilendirilme yapılacak
                } else {
                    if (cevap.result == '1') {
                        console.log(cevap.result)
                        console.log('Sipariş bilgileri gönderildi')
                        var host = window.location.host
                        //if (host == 'www.amazon.com' || host == 'www.abebooks.com') {
                            HataKontrolYap(250)
                            chrome.storage.local.set(
                                {
                                    KontrolUrl1: 'Hardcover',
                                    KontrolUrl2: 'Hardcover',
                                },
                                function () {
                                    //console.log("Birinci url kontrol edildi: " + deger);
                                    SekmeKapat(1)
                                }
                            )
                        //}
                        // setTimeout(function () {
                        //     UrunGetir()
                        // }, 2000)
                    } else {
                        console.log('else girdi')
                    }
                }
                console.log('Sipariş Tamamla Response!')
            },
            error: function (req, textStatus, errorThrown) {
                console.log('Ooops, something happened: ' + textStatus + ' ' + errorThrown)
                //SiparisTamamla()
            },
        })
    }
    })
    
}
const isValidUrl = urlString=> {
    var urlPattern = new RegExp('^(https?:\\/\\/)?'+ // validate protocol
  '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // validate domain name
  '((\\d{1,3}\\.){3}\\d{1,3}))'+ // validate OR ip (v4) address
  '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // validate port and path
  '(\\?[;&a-z\\d%_.~+=-]*)?'+ // validate query string
  '(\\#[-a-z\\d_]*)?$','i'); // validate fragment locator
return !!urlPattern.test(urlString);
}
var RunCount = 0
function UrunGetir() {
    var host = window.location.host
    if (host == 'www.jqueryscript.net') {
        chrome.storage.local.set({
            KontrolUrl1: '',
            KontrolUrl2: '',
            Titles: '',
            Price: '',
            Review: '',
            Rating: '',
            brokenlink: '',
            rank: '',
        })
        var host = window.location.host
        setTimeout(function () {
            chrome.storage.local.get(['MagazaAdi', 'isStarted', 'ApiUrl'], function (item) {
                if (item.isStarted == true) {
                    clearTimeout(HataKontrol)
                    HataKontrolYap(250)
                    console.log('Ürün Getirilecek!')
                    localStorage.clear()
                    ClearData();
                    localStorage.removeItem('LSAmazonUrunList')
                    var datam = {
                        getdata: '1',
                    }
                    console.log(datam)
                    console.log('Ürün getirilecek!')
                    $.ajax({
                        type: 'post',
                        url: item.ApiUrl + '/api/getProductData',
                        beforeSend: function (xhr) {
                            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
                        },
                        cache: false,
                        dataType: 'json',
                        data: datam,
                        success: function (cevap) {
                            console.log(cevap)
                            if (cevap.hata == 0 || cevap.data == null) {
                                chrome.storage.local.set(
                                    {
                                        UrunGetirildi: false,
                                        Durum: 'AppStarted',
                                    },
                                    function () {
                                        console.log('Hata: Ürün getirilemedi!')
                                        var d1 = new Date(),
                                            d2 = new Date(d1)
                                        d2.setMinutes(d1.getMinutes() + 30)
                                        var sure = d2.toLocaleString().substring(11, 19)
                                        var text =
                                            ' Kontrol edilecek sipariş kalmadı! Uygulama 30 dk bekletiliyor.' +
                                            sure +
                                            ' itibariyle tekrar başlatılacak.'
                                        clearTimeout(HataKontrol)
                                        HataKontrolYap(1, text)
                                        chrome.runtime.sendMessage({
                                            YenidenBaslat: true,
                                        })
                                        if (host == 'www.amazon.com' || host == 'www.abebooks.com') {
                                            SekmeKapat(2)
                                        }
                                    }
                                )
                            } else {
                                if (cevap.data) {
                                    console.log(cevap.data)
                                    //console.table(cevap.result);
                                    var data = cevap.data
                                    if (Array.isArray(data)) {
                                        localStorage.setItem('DataArray', JSON.stringify(cevap.data))
                                        chrome.storage.local.set(
                                            {
                                                UrunGetirildi: true,
                                                Durum: 'TypeKontrol',
                                                KontrolUrl1: '',
                                                dataArray: JSON.stringify(cevap.data),
                                            },
                                            function () {
                                                linkKontrolCount = 0
                                                urunKontrolCount = 0
                                                //BirinciLinkKontrol(0, 0)
                                                var dataArray = cevap.data
                                                if (dataArray.length > 0) {
                                                    if(isValidUrl(dataArray[0].ProductURL)) {
                                                        let url = new URL(dataArray[0].ProductURL)
                                                        SekmeAc('https://' + url.hostname)
                                                    } else {
                                                        let url = new URL(dataArray[1].ProductURL)
                                                        SekmeAc('https://' + url.hostname)
                                                    }
                                                }
                                                // dataArray.map((data, index) => {
                                                // SekmeAc('https://www.amazon.com')
                                                // SekmeAc('https://www.wayfair.com')
                                                // SekmeAc('https://www.amazon.de')
                                                // SekmeAc('https://www.amazon.fr')
                                                // SekmeAc('https://www.amazon.co.uk')
                                                // SekmeAc('https://www.abebooks.com')
                                                // SekmeAc('https://www.wayfair.com')
                                                // SekmeAc('https://www.wayfair.de')
                                                // SekmeAc('https://www.wayfair.co.uk')
                                                // SekmeAc('https://www.wayfair.ca')
                                                // SekmeAc('https://www.overstock.com')
                                                // SekmeAc('https://www.walmart.com')
                                                // SekmeAc('https://www.homedepot.com')
                                                // SekmeAc('https://www.markandday.com')
                                                // SekmeAc('https://www.boutiquerugs.com')
                                                // SekmeAc('https://www.rugs-direct.com')
                                                // });
                                                // if(data.KontrolUrl1 == data.KontrolUrl2)
                                                // {
                                                // chrome.storage.local.set({
                                                // "Durum": "FiyatKontrol"
                                                // },function () {
                                                // SiparisLinkleriGetir(data.ID, data.AmazonUrl, data.AbeUrl);
                                                // });

                                                // }else{link1

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

function dialogModal(message, background = 'limegreen') {
    let loader = document.createElement('div')
    $(loader).addClass('extDialog')
    $(loader).css('position', 'fixed')
    $(loader).css('min-height', '200px')
    $(loader).css('height', 'auto')
    $(loader).css('width', '200px')
    $(loader).css('background', background)
    $(loader).css('color', '#fff')
    $(loader).css('overflow-wrap', 'anywhere')
    $(loader).css('border-radius', '50%')
    $(loader).css('font-weight', 'bold')
    $(loader).css('bottom', '10px')
    $(loader).css('right', '0')
    $(loader).css('z-index', '9999')
    $(loader).css('display', 'flex')
    $(loader).css('justify-content', 'center')
    $(loader).css('align-items', 'center')
    $(loader).css('padding', '10px 10px 10px 10px')

    $(loader).html(message)
    document.body.append(loader)
    return loader
}

var count = 0

function BirinciLinkKontrol(KontrolUrl2, Sorgu) {
   
    chrome.storage.local.get(['Url', 'dataArray'], function (item) {
    var dataArray = JSON.parse(item.dataArray)
    if (dataArray.length > 0) {
        let url = "";
        console.log(dataArray[0].ProductURL);
        if(isValidUrl(dataArray[0].ProductURL)) {
            url = new URL(dataArray[0].ProductURL)
        } else {
            url = new URL(dataArray[1].ProductURL)
        }
        

        if ($('#glow-ingress-line2').length) {
            setTimeout(() => {
                document.querySelector("#nav-global-location-popover-link").click()
            },1000);
            setTimeout(function () {
                if (url.hostname.indexOf('amazon.de') >= 0 && $('#glow-ingress-line2').text().trim().indexOf('10115') == -1) {
                    document.querySelector('#GLUXZipUpdateInput').value = '10115'
                    document.querySelector('#GLUXZipUpdate > span > input').click()
                setTimeout(function () {
                if(document.querySelector('#a-popover-1 > div > div.a-popover-footer > span > span > span > button'))
                    document.querySelector('#a-popover-1 > div > div.a-popover-footer > span > span > span > button').click()
                if(document.querySelector("#GLUXConfirmClose"))
                    document.querySelector("#GLUXConfirmClose").click();
                }, 1000)
                }
                    
                if (url.hostname.indexOf('amazon.co.uk') >= 0 && $('#glow-ingress-line2').text().trim().indexOf('E1') == -1) {
                    document.querySelector('#GLUXZipUpdateInput').value = 'E1 0AA'
                    document.querySelector('#GLUXZipUpdate > span > input').click()
                setTimeout(function () {
                if(document.querySelector('#a-popover-1 > div > div.a-popover-footer > span > span > span > button'))
                    document.querySelector('#a-popover-1 > div > div.a-popover-footer > span > span > span > button').click()
                if(document.querySelector("#GLUXConfirmClose"))
                    document.querySelector("#GLUXConfirmClose").click();
                }, 1000)
                }
                    
                if(url.hostname.indexOf('amazon.com') >= 0 && $('#glow-ingress-line2').text().trim().indexOf('90001')==-1) {
                    document.querySelector('#GLUXZipUpdateInput').value = '90001'
                    document.querySelector('#GLUXZipUpdate > span > input').click()
                setTimeout(function () {
                if(document.querySelector('#a-popover-1 > div > div.a-popover-footer > span > span > span > button'))
                    document.querySelector('#a-popover-1 > div > div.a-popover-footer > span > span > span > button').click()
                if(document.querySelector("#GLUXConfirmClose"))
                    document.querySelector("#GLUXConfirmClose").click();
                }, 1000)
                }
                    
                if(url.hostname.indexOf('amazon.fr') >= 0 && $('#glow-ingress-line2').text().trim().indexOf('75000')==-1) {
                    document.querySelector('#GLUXZipUpdateInput').value = '75000'
                    document.querySelector('#GLUXZipUpdate > span > input').click()
                setTimeout(function () {
                if(document.querySelector('#a-popover-1 > div > div.a-popover-footer > span > span > span > button'))
                    document.querySelector('#a-popover-1 > div > div.a-popover-footer > span > span > span > button').click()
                if(document.querySelector("#GLUXConfirmClose"))
                    document.querySelector("#GLUXConfirmClose").click();
                }, 1000)
                }
                    
                    
            }, 2000)
        }
    }
    setTimeout(() => {
        
            var host = window.location.host
            
            console.table(dataArray)
            let istek = []
            let loader = dialogModal(`Loading...`)
            let counter = 1
    
            axios.defaults.withCredentials = true
    
            dataArray.map(async (data, index) => {
    
                chrome.runtime.sendMessage({
                    proxy: true,
                })

                const requests=  await new Promise(async (resolve, reject) => {
                    let url=data.ProductURL.replace("http://", "https://")
                   await  axios.get(url,{},
                    {
                        headers: {
                            'Cache-Control': 'no-cache',
                            'Pragma': 'no-cache',
                            'Expires': '0',
                            cookie: document.cookie,
                        },
                    })
                        .then(async (response) => {
                            var host = window.location.host
                            let dataHtml = response.data
                            let html = $.parseHTML(dataHtml)
                            let in_stock = true
                            var fiyat = null
                            var review = null
                            var rating = null
                            var rank = null
                            var dolar = 0
                            var cent = 0
                            if (data.ProductURL.indexOf('boutiquerugs.com') >= 0) {
                                if ($('body', html).text().includes('404 Error - Page not found')) {
                                    brokenlink = 1
                                } else {
                                    // chrome.storage.local.get(['Size'], function (item) {
                                    //     $('div.ProductForm__Variants div.ProductForm__Option ul li label', html).each(function () {
                                    //         if ($(this).text().replace(/\D/g, '') == item.Size) {
                                    //             $(this).click()
                                    //         }
                                    //     })
                                    // })
                                    
                                        let in_stock = true
                                        if ($('#klaviyoInStockNotify', html).attr('style') === 'display: flex !important') 
                                            in_stock = false

                                        if ($('span.price.price--withoutTax.color-red.price-custom-now', html).length)
                                            fiyat = $('span.price.price--withoutTax.color-red.price-custom-now', html).text().split('$')[1]
                                        if ($('#discounted-price', html).length) 
                                            fiyat = $('#discounted-price', html).text().split('$')[1]
                                        if($("meta[property='product:price:amount']",html).length)
                                            fiyat = $("meta[property='product:price:amount']",html).attr('content');
                                        if($("#size-list > li.HorizontalList__Item.Rectangle.selectedVariant > label > span.price-range", html).length)
                                            fiyat = $("#size-list > li.HorizontalList__Item.Rectangle.selectedVariant > label > span.price-range",html).text().split('$')[1];

                                        if (
                                            $("#yotpo-star-ratings-app > div > div > div.yotpo-sr-bottom-line-right-panel > div", html).length
                                        )
                                            review = $("#yotpo-star-ratings-app > div > div > div.yotpo-sr-bottom-line-right-panel > div", html).text().trim().split('(')[1].split(')')[0]
                                        if (
                                            $(
                                                'div.productView > section:nth-child(1) > div > div.yotpo.bottomLine.yotpo-medium > div > div.standalone-bottomline > div.yotpo-bottomline.pull-left.star-clickable > a',
                                                html
                                            ).length
                                        )
                                            rating = $(
                                                'div.productView > section:nth-child(1) > div > div.yotpo.bottomLine.yotpo-medium > div > div.standalone-bottomline > div.yotpo-bottomline.pull-left.star-clickable > a',
                                                html
                                            )
                                                .attr('aria-label')
                                                .split(' ')[0]

                                        chrome.storage.local.set(
                                            {
                                                Titles: 'deneme',
                                                Price: fiyat,
                                                Review: review,
                                                Rating: rating,
                                                brokenlink: 0,
                                                Stock: in_stock,
                                            },
                                            function () {
                                                //console.log("Birinci url kontrol edildi: " + deger);
                                                console.log('Fiyat:' + fiyat + ' Review:' + review + ' Rating:' + rating)
                                            }
                                        )
                                        HataKontrolYap(250)
                                }
                            }
                            if (data.ProductURL.indexOf('www.kohls.com') >= 0) {
                                
                                    
                                        let in_stock = true
                                        if ($('#klaviyoInStockNotify', html).attr('style') === 'display: flex !important') 
                                            in_stock = false

                                        if ($("#pdpprice-price-container > p > span", html).length)
                                            fiyat = $("#pdpprice-price-container > p > span", html).text().trim().split('$')[1];
                                        
                                        if ($("#PDP_block1 > div.pdp-main-bazarvoice-ratings > div > div > button > div.bv_avgRating_component_container.notranslate", html).length
                                        )
                                            rating = $("#PDP_block1 > div.pdp-main-bazarvoice-ratings > div > div > button > div.bv_avgRating_component_container.notranslate", html).text();
                                        if (
                                            $("#PDP_block1 > div.pdp-main-bazarvoice-ratings > div > div > button > div.bv_numReviews_component_container > div", html).length
                                        )
                                            review = $("#PDP_block1 > div.pdp-main-bazarvoice-ratings > div > div > button > div.bv_numReviews_component_container > div", html).text().split('(')[1].split(')')[0]

                                        chrome.storage.local.set(
                                            {
                                                Titles: 'deneme',
                                                Price: fiyat,
                                                Review: review,
                                                Rating: rating,
                                                brokenlink: 0,
                                                Stock: in_stock,
                                            },
                                            function () {
                                                //console.log("Birinci url kontrol edildi: " + deger);
                                                console.log('Fiyat:' + fiyat + ' Review:' + review + ' Rating:' + rating)
                                            }
                                        )
                                        HataKontrolYap(250)
                                
                            }
                            if (data.ProductURL.indexOf('www.rugs-direct.com') >= 0) {
                                if (
                                    $(
                                        '#pdp-container > div.right-panel > div.buybox > div > div.product-form > div.drawer-buttons > div.btn-drawer.select-size',
                                        html
                                    ).length
                                )
                                    $(
                                        '#pdp-container > div.right-panel > div.buybox > div > div.product-form > div.drawer-buttons > div.btn-drawer.select-size',
                                        html
                                    ).click()

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

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

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

                                        if (
                                            $(
                                                '#pdp-prod-name-container > div.prod_review > a > div > div > div.standalone-bottomline > div.yotpo-bottomline.pull-left.star-clickable > a',
                                                html
                                            ).length
                                        )
                                            var review = $(
                                                '#pdp-prod-name-container > div.prod_review > a > div > div > div.standalone-bottomline > div.yotpo-bottomline.pull-left.star-clickable > a',
                                                html
                                            )
                                                .text()
                                                .split(' ')[0]

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

                                        if (!option) fiyat = 0
                                        chrome.storage.local.set(
                                            {
                                                Titles: 'deneme',
                                                Price: fiyat,
                                                Review: review,
                                                Rating: rating,
                                                Stock: true,
                                                brokenlink: 0,
                                            },
                                            function () {
                                                console.log('Fiyat:' + fiyat + ' Review:' + review + ' Rating:' + rating)
                                            }
                                        )
                                        HataKontrolYap(250)
                                    }, 5000)
                                }
                            }
                            if (data.ProductURL.indexOf('markandday.com') >= 0) {
                                if ($('body', html).text().includes('404 Page Not Found')) {
                                    brokenlink = 1
                                    chrome.storage.local.set(
                                        {
                                            Titles: 'deneme',
                                            Price: '',
                                            Review: '',
                                            Rating: '',
                                            Stock: true,
                                            brokenlink: 1,
                                        },
                                        function () {
                                            //console.log("Birinci url kontrol edildi: " + deger);
                                            console.log('Link is broken')
                                        }
                                    )
                                } else {
                                    let in_stock = true
                                    if ($('#addbuttons:hidden', html).attr('id')) in_stock = false
                                    if ($('#addbuttons', html).attr('id') === undefined) in_stock = false

                                    if ($('#ProductPrice', html).length) var fiyat = $('#ProductPrice', html).text().split('$')[1]

                                    if ($('#currentvariantprice1', html).length) var fiyat = $('#currentvariantprice1', html).text().split('$')[1]

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

                                    if (
                                        $(
                                            '#ProductSection > div.product-single > div > div.grid__item.post-large--one-half.product_single-details > div > div.product-single__prices > div.yotpo.bottomLine.yotpo-medium > div > div.standalone-bottomline > div.yotpo-bottomline.pull-left.star-clickable > a',
                                            html
                                        ).length
                                    )
                                        var rating = $(
                                            '#ProductSection > div.product-single > div > div.grid__item.post-large--one-half.product_single-details > div > div.product-single__prices > div.yotpo.bottomLine.yotpo-medium > div > div.standalone-bottomline > div.yotpo-bottomline.pull-left.star-clickable > a',
                                            html
                                        )
                                            .attr('aria-label')
                                            .split(' ')[0]
                                    chrome.storage.local.set(
                                        {
                                            Titles: 'deneme',
                                            Price: fiyat,
                                            Review: review,
                                            Rating: rating,
                                            Stock: in_stock,
                                            brokenlink: 0,
                                        },
                                        function () {
                                            console.log('Fiyat:' + fiyat + ' Review:' + review + ' Rating:' + rating)
                                        }
                                    )
                                    HataKontrolYap(250)
                                }
                            }
                            if (data.ProductURL.indexOf('www.homedepot.com') >= 0) {
                                if ($('#ajaxPrice > span.price__dollars', html).length)
                                     dolar = $('#ajaxPrice > span.price__dollars', html).text().trim()
                                else if ($('div.price-format__large.price-format__main-price  span:nth-child(2)', html).length)
                                     dolar = $('div.price-format__large.price-format__main-price  span:nth-child(2)', html)
                                        .text()
                                        .trim()
                                else if ($('#standard-price > div > div > span:nth-child(2)', html).length)
                                     dolar = $('#standard-price > div > div > span:nth-child(2)', html).text().trim()
                                if ($('span.price__cents', html).length) 
                                     cent = $('span.price__cents', html).text()
                                if (
                                    $('div.price-format__large.price-format__main-price span:nth-child(3)', html)
                                        .length
                                )
                                     cent = $(
                                        'div.price-format__large.price-format__main-price span:nth-child(3)',
                                        html
                                    ).text()
                                if ($('#standard-price > div > div > span:nth-child(3)', html).length)
                                     cent = $('#standard-price > div > div > span:nth-child(3)', html).text()

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

                                if ($('#BVRRSummaryContainer  span.product-details__review-count', html).length)
                                    review = $('#BVRRSummaryContainer  span.product-details__review-count', html)
                                        .text()
                                        .split('(')[1]
                                        .split(')')[0]
                                if ($('#product-details__review__target > span.product-details__review-count', html).length)
                                    review = $('#product-details__review__target > span.product-details__review-count', html)
                                        .text()
                                        .split('(')[1]
                                        .split(')')[0]
                                if ($('#BVRRSummaryContainer > div > div:nth-child(2) > a > span > div > span', html).length) {
                                    rating = $('#BVRRSummaryContainer > div > div:nth-child(2) > a > span > div > span', html)
                                        .parent.attr('title')
                                        .split(' ')[0]
                                }
                                    
                                if ($('div.loader__content > a', html).length) {
                                    rating = $(' div.loader__content > a', html).attr('title').split(' ')[0]
                                }
                                    

                                if ($('a.product-details__rating-container', html).length) {
                                    rating = $('a.product-details__rating-container', html)
                                        .attr('title')
                                        .split(' ')[0]
                                }
                                    

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

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

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

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

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

                                        chrome.storage.local.set(
                                            {
                                                Titles: 'deneme',
                                                Price: fiyat,
                                                Review: review,
                                                Rating: rating,
                                                brokenlink: 0,
                                                Stock: in_stock,
                                            },
                                            function () {
                                                //console.log("Birinci url kontrol edildi: " + deger);
                                                console.log('Fiyat:' + fiyat + ' Review:' + review + ' Rating:' + rating)
                                            }
                                        )
                                        HataKontrolYap(250)
                                    }
                                }
                            }
                            if (
                                data.ProductURL.indexOf('www.wayfair.com') >= 0 ||
                                data.ProductURL.indexOf('www.wayfair.de') >= 0 ||
                                data.ProductURL.indexOf('www.wayfair.co.uk') >= 0 ||
                                data.ProductURL.indexOf('www.wayfair.ca') >= 0
                            ) {
                                //console.log(dataHtml);
                                fiyat = dataHtml.price ? dataHtml.price.salePrice : 0;
                                review = dataHtml.soloReviewSection ? dataHtml.soloReviewSection.review_rating : 0;
                                rating = dataHtml.soloReviewSection ? dataHtml.soloReviewSection.rating_count : 0;
                                // if ((window.location.href !== item.Url) && (document.querySelector("#sf-ui-product-details\\:\\:application") === null)) {
                                //     chrome.storage.local.set({
                                //         'KontrolUrl1': 'Hardcover',
                                //         'KontrolUrl2': 'Hardcover',
                                //         'Titles': 'deneme',
                                //         'Price': "",
                                //         'Review': "",
                                //         'Rating': "",
                                //         'Stock' : true,
                                //         'brokenlink': 1
                                //     }, function () {
                                //         //console.log("Birinci url kontrol edildi: " + deger);
                                //         console.log("Link is broken");
                                //         SekmeKapat(1);
                                //     });
                                // }
                                // else {
                                // let currency = '$'
                                // let arrayIndex = 1
                                // if (data.ProductURL.indexOf('www.wayfair.de') >= 0) {
                                //     currency = '€'
                                //     arrayIndex = 0
                                // }

                                // if (data.ProductURL.indexOf('www.wayfair.co.uk') >= 0) {
                                //     currency = '£'
                                //     arrayIndex = 1
                                // }

                                // if ($('div.BasePriceBlock > span', html).length)
                                //     var fiyat = $('div.BasePriceBlock > span', html).text().split(currency)[arrayIndex].trim()
                                // if ($('span.pl-Price-V2.pl-Price-V2--5000', html).length)
                                //     var fiyat = $('span.pl-Price-V2.pl-Price-V2--5000', html).text().split(currency)[arrayIndex].trim()
                                // if ($('span.ProductRatingNumberWithCount-count', html).length)
                                //     var review = $('span.ProductRatingNumberWithCount-count', html).text().split(' ')[0]
                                // if ($('span.ProductRatingNumberWithCount-rating', html).length)
                                //     var rating = $('span.ProductRatingNumberWithCount-rating', html).text()

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

                                console.log('Fiyat:' + fiyat + ' Review:' + review + ' Rating:' + rating)
                                chrome.storage.local.set(
                                    {
                                        Titles: 'deneme',
                                        Price: fiyat,
                                        Review: review,
                                        Rating: rating,
                                        brokenlink: 0,
                                        Stock: in_stock,
                                    },
                                    function () {
                                        //console.log("Birinci url kontrol edildi: " + deger);
                                        //console.log("Fiyat:" + fiyat + " Review:" + review + " Rating:" + rating);
                                    }
                                )
                                HataKontrolYap(250)

                                //}
                            }
                            if (data.ProductURL.indexOf('www.walmart.com') >= 0) {
                                if ($('span.w_B3.w_B4.mb6.tc', html).length) {
                                    brokenlink = 1
                                    chrome.storage.local.set(
                                        {
                                            Titles: 'deneme',
                                            Price: '',
                                            Review: '',
                                            Rating: '',
                                            Stock: true,
                                            brokenlink: '1',
                                        },
                                        function () {
                                            //console.log("Birinci url kontrol edildi: " + deger);
                                            console.log('Link is broken')
                                            // SekmeKapat(1)
                                        }
                                    )
                                } else {
                                    var timeoutId = 0;
                                    if($('p:contains("Press & Hold")').length) {
                                        $('p:contains("Press & Hold")').on('mousedown', function() {
                                            timeoutId = setTimeout(myFunction, 10000);
                                        }).on('mouseup mouseleave', function() {
                                            clearTimeout(timeoutId);
                                        });
                                    }
                                   
                                    
                                    let in_stock = true
                                    if (
                                        $(
                                            '#__next > div:nth-child(1) > div > div > div.flex-auto.relative.z-1 > div > section > main > div > div:nth-child(2) > div > div.w_CM.w_DL.w_CQ > div > div > div.slide-sticky-buy-box-up.z-5 > div > div > div.pt3.f4.light-gray > div > div > div.b.gray.lh-copy.pt2-m.flex.fr-m.\\"f4.tr',
                                            html
                                        ).length
                                    )
                                        in_stock = false

                                    if (
                                        $(
                                            '#price > div > span.hide-content.display-inline-block-m > span > span.price-group > span.price-characteristic',
                                            html
                                        ).length
                                    )
                                        var fiyat = $(
                                            '#price > div > span.hide-content.display-inline-block-m > span > span.price-group > span.price-characteristic',
                                            html
                                        ).attr('content')
                                    if ($('span[itemprop=price]', html).length) var fiyat = $('span[itemprop=price]', html).text().split('$')[1]
                                    if (
                                        $(
                                            'div.prod-productsecondaryinformation.display-inline-block.prod-SecondaryInfo > div.secondary-info-margin-right.secondary-margin-bottom.display-inline-block.valign-middle > div > span.stars-reviews.font-normal > span',
                                            html
                                        ).length
                                    )
                                        var review = $(
                                            'div.prod-productsecondaryinformation.display-inline-block.prod-SecondaryInfo > div.secondary-info-margin-right.secondary-margin-bottom.display-inline-block.valign-middle > div > span.stars-reviews.font-normal > span',
                                            html
                                        )
                                            .text()
                                            .split(' ')[0]
                                    if (
                                        $(
                                            'body > div.js-content > div.page-wrapper > div > div.js-body-content > div > div.atf-content > div > div:nth-child(1) > div > div > div > div > div.Grid > div.product-atf > div > div:nth-child(3) > div > div.prod-productsecondaryinformation.display-inline-block.prod-SecondaryInfo > div.secondary-info-margin-right.secondary-margin-bottom.display-inline-block.valign-middle > div > span.stars-container',
                                            html
                                        ).length
                                    )
                                        var rating = $(
                                            'body > div.js-content > div.page-wrapper > div > div.js-body-content > div > div.atf-content > div > div:nth-child(1) > div > div > div > div > div.Grid > div.product-atf > div > div:nth-child(3) > div > div.prod-productsecondaryinformation.display-inline-block.prod-SecondaryInfo > div.secondary-info-margin-right.secondary-margin-bottom.display-inline-block.valign-middle > div > span.stars-container',
                                            html
                                        )
                                            .attr('aria-label')
                                            .split(' ')[0]
                                    

                                    if($("span.f7.rating-number", html).length) {
                                        rating = $("span.f7.rating-number", html).text().split('(')[1].split(')')[0];
                                    }
                                    if($('a[link-identifier="reviewsLink"]',html).length){
                                        review = $('a[link-identifier="reviewsLink"]',html).text().split(' ')[0]
                                    }
                                    chrome.storage.local.set(
                                        {
                                            Titles: 'deneme',
                                            Price: fiyat,
                                            Review: review,
                                            Rating: rating,
                                            brokenlink: '0',
                                            Stock: in_stock,
                                        },
                                        function () {
                                            //console.log("Birinci url kontrol edildi: " + deger);
                                            console.log('Fiyat:' + fiyat + ' Review:' + review + ' Rating:' + rating)
                                        }
                                    )
                                    HataKontrolYap(250)
                                }
                            }
                            if (
                                data.ProductURL.indexOf('www.amazon.com') >= 0 ||
                                data.ProductURL.indexOf('www.amazon.de') >= 0 ||
                                data.ProductURL.indexOf('www.amazon.co.uk') >= 0 ||
                                data.ProductURL.indexOf('www.amazon.fr') >= 0
                            ) {
                                
                                var aramaTextBox = $('#twotabsearchtextbox', html)
                                var myElem = $('title', html)
                                // if ($('#glow-ingress-line2', html).text().trim() == 'Select your address') {
                                //     $('#nav-global-location-popover-link', html).click()
                                //     setTimeout(function () {
                                //         document.querySelector('#GLUXZipUpdateInput', html).value = '90001'
                                //         document.querySelector('#GLUXZipUpdate > span > input', html).click()
                                //         document
                                //             .querySelector('#a-popover-1 > div > div.a-popover-footer > span > span > span > button', html)
                                //             .click()
                                //     }, 1000)
                                // }

                                if ($('#productDetails_detailBullets_sections1', html).length) {
                                    $('#productDetails_detailBullets_sections1 > tbody > tr > th', html).each(function () {
                                        if ($(this).text().trim() == 'Best Sellers Rank') {
                                            var categoryName = $('#wayfinding-breadcrumbs_feature_div > ul > li:last-child > span > a', html)
                                                .text()
                                                .trim()
                                            var rankTemp = $(this).parent().find('span').find('span').text().trim()
                                            var r = $(this).next().find('span').last().text().trim()
                                            rank = r.split(' ')[0].split('#')[1]
                                        }
                                    })
                                }

                                let currency = '$'
                                let arrayIndex = 1
                                if (data.ProductURL.indexOf('www.amazon.de') >= 0) {
                                    currency = '€'
                                    arrayIndex = 0
                                }

                                if (data.ProductURL.indexOf('www.amazon.co.uk') >= 0) {
                                    currency = '£'
                                    arrayIndex = 1
                                }

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

                                if ($('#availability span', html).length) {
                                    if ($('#availability span', html).text().trim() == 'Currently unavailable.') 
                                        in_stock = false
                                    if ($('#availability span', html).text().trim() == 'Temporarily out of stock.') 
                                        in_stock = false
                                }
                                if ($('#priceblock_ourprice', html).length)
                                    fiyat = $('#priceblock_ourprice', html).text().trim().split(currency)[arrayIndex]
                                if ($('#priceblock_dealprice', html).length)
                                    fiyat = $('#priceblock_dealprice', html).text().trim().split(currency)[arrayIndex]
                        
                                if (
                                    $('#corePrice_desktop span.a-price.a-text-price.a-size-medium.apexPriceToPay  span:nth-child(2)', html).length
                                ) {
                                    fiyat = $(
                                        '#corePrice_desktop span.a-price.a-text-price.a-size-medium.apexPriceToPay  span:nth-child(2)',
                                        html
                                    )
                                        .text()
                                        .trim()
                                        .split(currency)[arrayIndex]
                                    }
                                if ($(
                                        '#corePriceDisplay_desktop_feature_div > div.a-section.a-spacing-none.aok-align-center > span.a-price.aok-align-center.priceToPay > span.a-offscreen',
                                        html
                                    ).length
                                ) {
                                    fiyat = $('#corePriceDisplay_desktop_feature_div > div.a-section.a-spacing-none.aok-align-center > span.a-price.aok-align-center.priceToPay > span.a-offscreen',html)
                                        .text()
                                        .trim()
                                        .split(currency)[arrayIndex]
                                    }
                                if($('input#attach-base-product-price',html).length) {
                                    fiyat = $('#attach-base-product-price', html).prop("defaultValue");
                                }
                                if ($('#acrCustomerReviewText', html).length) 
                                    review = $('#acrCustomerReviewText', html).text().split(' ')[0]
                                if ($('#acrPopover > span.a-declarative > a > i > span', html).length)
                                    rating = $('#acrPopover > span.a-declarative > a > i > span', html).text().split(' ')[0]

                                if(rank == undefined)
                                    rank = null;
                                
                                chrome.storage.local.set(
                                    {
                                        Titles: 'deneme',
                                        Price: fiyat,
                                        Review: review,
                                        Rating: rating,
                                        brokenlink: 0,
                                        Stock: in_stock,
                                        rank: rank,
                                    },
                                    function () {
                                        //console.log("Birinci url kontrol edildi: " + deger);
                                        console.log('Fiyat:' + fiyat + ' Review:' + review + ' Rating:' + rating)
                                    }
                                )

                                HataKontrolYap(250);
                            }

                            $(loader).html(`İşleniyor : ${counter + '/' + dataArray.length}`)
                            counter++
                            resolve({
                                ID: data.ID,
                                ProductURL: data.ProductURL,
                                Size: data.Size,
                                BrandSKU: data.BrandSKU,
                                Price: fiyat,
                                Review: review,
                                Rating: rating,
                                Stock: in_stock ?? true,
                                brokenlink: 0,
                                rank: rank,
                            })
                        })
                        .catch((e) => {
                            reject(e)
                        })
                });
                istek.push(requests)
                   
                })
                setTimeout(() => {
                    
                
                 Promise.all(istek)
                    .then((values) => {
                        console.log(values)
                        $(loader).html('Kayıt ediliyor!')
                        SiparisTamamla(values)
                    })
                    .catch((e) => {
                        console.log(e, 'Hata!')
                        $(loader).remove()
                    })
            }, 5000);
            },3000)
    });

       
   
}

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

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

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

function SiparisLinkleriGetir(id, AmazonUrl, AbeUrl) {
    chrome.storage.local.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 AmzUrunList = []

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

var AmzOrderCompleteCheckCount = 0

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

var AmzOrderCompleteCheckCount = 0

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

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

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

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

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

    return strText
}

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

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

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

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

function ClearData() {
    AppLog(log)
    AppLogGonder()
    sessionStorage.clear()
    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.local.set(
        {
            AppLog: test,
        },
        function () {}
    )
}

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

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

var HataKontrol

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)
            if (msj2 == undefined) {
                chrome.runtime.sendMessage({
                    HataYenile: true,
                })

                chrome.storage.local.set(
                    {
                        KontrolUrl1: 'Hardcover',
                        KontrolUrl2: 'Hardcover',
                    },
                    function () {
                        //console.log("Birinci url kontrol edildi: " + deger);
                    }
                )
            }

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

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

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

            // }, 3000);

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

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

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

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

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

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

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