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

var kontrol

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

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

var linkKontrolCount = 0
var urunKontrolCount = 0

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

    for (key in changes) {
        if (key == 'KontrolUrl1' || key == 'KontrolUrl2') {
            storageChange = changes[key]
            if (storageChange.newValue.length > 0) {
                linkKontrolCount++
                //alert(linkKontrolCount);
                if (linkKontrolCount == 2) {
                    setTimeout(function () {
                        SiparisTamamla()
                    }, 2000)
                }
            }
        } else if (key == 'AmzUrunList' || key == 'AbeUrunList') {
            storageChange = changes[key]
            if (storageChange.newValue != undefined && storageChange.newValue != null) {
                urunKontrolCount++
                if (urunKontrolCount == 2) {
                    setTimeout(function () {
                        console.log(' UrunListeleriniGonder(); onchanged çağrıldı')
                        UrunListeleriniGonder()
                    }, 2000)
                }
            }
        } else {
        }
    }
})

$(document).ready(function () {
    var host = window.location.host
    var href = window.location.href
    chrome.storage.sync.get(
        [
            'isStarted',
            'UrunGetirildi',
            'Durum',
            'KontrolUrl1',
            'KontrolUrl1Hata',
            'KontrolUrl2Hata',
            'KontrolUrl2',
            'UrunFiyat',
            'AmzPageCount',
            'AbePageCount',
            'AmazonUrl',
            'AbeUrl',
            'UrunFiyat',
            'MagazaAdi',
            'RequestTime',
        ],
        function (item) {
            setTimeout(function () {
                if (item.isStarted == true) {
                    MagazaAdi = item.MagazaAdi
                    AmazonUrl = item.AmazonUrl
                    console.log(item.Durum)
                    AbeUrl = item.AbeUrl
                    var urll = window.location.href
                    if (urll == 'https://www.amazon.com/gp/errors/404.html') {
                        UrunZararYaz()
                    }
                    console.log(href)
                    if (href == 'https://www.amazon.com/?ref_=abn_logo') {
                        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)
                        } else if (item.Durum == 'FiyatKontrol') {
                            console.log('Şuan yapılan işlem: ' + item.Durum)
                        } else {
                            console.log('düşün')
                            //UrunGetir();
                        }
                    } else {
                        console.log('TypeKontrol')
                        //HataKontrolYap(250);
                        if (item.Durum == 'TypeKontrol') {
                            console.log('TypeKontrol')
                            var KontrolUrl1 = item.KontrolUrl1
                            var KontrolUrl2 = item.KontrolUrl2
                            var KontrolUrl1Hata = parseInt(item.KontrolUrl1Hata)
                            var KontrolUrl2Hata = parseInt(item.KontrolUrl2Hata)
                            var LinkKontrolSayfasi = parseInt(QueryStringOku('Validate'))
                            BirinciLinkKontrol(KontrolUrl2, KontrolUrl1Hata)
                            // setTimeout(function () {
                            // var TipKontrolYap = LinkKontrolSayfasi == 1 ? BirinciLinkKontrol(KontrolUrl2, KontrolUrl1Hata) : IkinciLinkKontrol(KontrolUrl1, KontrolUrl2Hata);
                            // }, 500);
                        } else if (item.Durum == 'FiyatKontrol') {
                            var Fiyat = item.UrunFiyat
                            var AmzPageCount = 0
                            var AbePageCount = 0
                            AmazonUrl = item.AmazonUrl
                            AbeUrl = item.AbeUrl
                            var FiyatKontrolSayfasi = QueryStringOku('PgNm')
                            if (FiyatKontrolSayfasi != null && FiyatKontrolSayfasi.length > 0) {
                                setTimeout(function () {
                                    var FiyatKontrolYap =
                                        FiyatKontrolSayfasi == 'Abe'
                                            ? AbeFiyatKontrol(Fiyat, AbePageCount, AbeUrl)
                                            : AmazonFiyatKontrol(Fiyat, AmzPageCount, AmazonUrl)
                                    console.log('FiyatKontrolYap')
                                }, 500)
                            }
                        } else if (item.Durum == 'UrunAl') {
                            AmazonUrl = item.AmazonUrl
                            AbeUrl = item.AbeUrl
                            var UrunSatinAlmaSayfasi = QueryStringOku('PgNm')
                            var UrunSepetSayfasi = QueryStringOku('Basket')
                            var AddAdres = QueryStringOku('AddAdres')
                            var AmzSepetBosalt = QueryStringOku('Sil')
                            var AbeBilling = QueryStringOku('Billing')
                            var isAbePlaceOrder = QueryStringOku('Complete')
                            if (UrunSatinAlmaSayfasi != null && UrunSatinAlmaSayfasi.length > 0) {
                                if (UrunSepetSayfasi != null && UrunSepetSayfasi.length > 0) {
                                    setTimeout(function () {
                                        var HangiSayfa =
                                            UrunSatinAlmaSayfasi == 'Abe' ? AbeBasketPage() : AmzBasketPage()
                                    }, 500)
                                } else if (AddAdres != null && AddAdres.length > 0) {
                                    setTimeout(function () {
                                        var HangiSayfa =
                                            UrunSatinAlmaSayfasi == 'Abe' ? AbeAdresSilme() : 'AmzAdresEkle()'
                                    }, 500)
                                } else if (AmzSepetBosalt != null && AmzSepetBosalt.length > 0) {
                                    setTimeout(function () {
                                        AmzBasketBosalt()
                                    }, 500)
                                } else if (AbeBilling != null && AbeBilling != 'false' && AbeBilling.length > 0) {
                                    setTimeout(function () {
                                        AbeEditBilling()
                                    }, 500)
                                } else if (isAbePlaceOrder != null && isAbePlaceOrder.length > 0) {
                                    setTimeout(function () {
                                        AbeOrderComplete()
                                        //incele
                                    }, 500)
                                } else {
                                    setTimeout(function () {
                                        var HangiSayfa =
                                            UrunSatinAlmaSayfasi == 'Abe'
                                                ? AbeUrunAl(item.UrunFiyat)
                                                : AmzUrunAl(item.UrunFiyat)
                                    }, 500)
                                }
                            } else if (window.location.href == 'https://www.abebooks.com/servlet/ShoppingBasket') {
                                AbeBasketBosalt()
                            } else if (window.location.href == 'https://www.abebooks.com/servlet/PaymentDetail?ac=f') {
                                AbeSaveBilling()
                            } else if (
                                window.location.href == 'https://www.abebooks.com/servlet/OrderSummary' &&
                                document.referrer == 'https://www.abebooks.com/servlet/PaymentDetail?ac=f'
                            ) {
                                AbeOrderComplete()
                            } else if (window.location.href == 'https://www.abebooks.com/servlet/ShippingAddress') {
                                var textMessage = $('.errorMessage').text()
                                if (textMessage.length > 0) {
                                    HataKontrolYap(1, textMessage.trim())
                                    console.log('Hata var:' + textMessage.trim())
                                    UrunZararYaz()
                                } else {
                                    //AbeAdresEkle();

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

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

function 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).html(message)
    document.body.append(loader)
    return loader
}

function SiparisTamamla(dataArray) {
    chrome.storage.sync.get(['MagazaAdi', 'UrunID', 'tracking', 'kargoFirma', 'ApiUrl'], function (item) {
        //MTip: Mağaza Tip (Amazon (0), Abe (1))

        var datam = {
            magazaDeger: item.MagazaAdi,
            TrackingArray: dataArray,
            tip: 'newOrderTrackEndToplu',
        }
        console.log(datam)
        $.ajax({
            type: 'post',
            url: item.ApiUrl + 'ExtensionWebServis/ajaxCall',
            beforeSend: function (xhr) {
                xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
            },
            cache: false,
            dataType: 'json',
            data: datam,
            success: function (cevap) {
                console.log(cevap)
                if (cevap.hata == '0') {
                    console.log('Hata: Tracking Bilgileri Gönderilemedi!')

                    //Hata alındı bilgilendirilme yapılacak
                } else {
                    if (cevap.result) {
                        console.log(cevap.result)
                        console.log('Tracking bilgileri gönderildi')
                        setTimeout(function () {
                            SekmeKapat()
                            chrome.storage.local.set({ isStarted: false }, function () {
                                chrome.storage.sync.remove(['isStarted'], function () {})
                            })
                        }, 2000)
                    } else {
                        console.log('else girdi')
                        SekmeKapat()
                    }
                }
            },
            error: function (req, textStatus, errorThrown) {
                console.log('Ooops, something happened: ' + textStatus + ' ' + errorThrown)
                //SiparisTamamla()
            },
        })
    })
}

var RunCount = 0
function UrunGetir() {
    chrome.storage.sync.set({
        KontrolUrl1: '',
        KontrolUrl2: '',
        Titles: '',
        tracking: '',
        kargoFirma: '',
    })
    var host = window.location.host
    setTimeout(function () {
        chrome.storage.sync.get(['MagazaAdi', 'PcName', 'ApiUrl'], function (item) {
            clearTimeout(HataKontrol)
            //HataKontrolYap(75);
            console.log('Ürün Getirilecek!')
            localStorage.clear()
            localStorage.removeItem('LSAmazonUrunList')
            var datam = {
                magazaDeger: item.MagazaAdi,
                pcAd: item.PcName,
                tip: 'newOrderTrackStartToplu',
            }
            console.log(datam)
            console.log('Ürün getirilecek!')
            $.ajax({
                type: 'post',
                url: item.ApiUrl + 'ExtensionWebServis/ajaxCall',
                beforeSend: function (xhr) {
                    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
                },
                cache: false,
                dataType: 'json',
                data: datam,
                timeout: 5000,
                success: function (cevap) {
                    console.log(cevap)
                    // if (cevap.hata == 0 || cevap.data==null) {
                    // chrome.storage.sync.set({
                    // "UrunGetirildi": false,
                    // "Durum": "AppStarted"
                    // }, function () {
                    // console.log("Hata: Ürün getirilemedi!");
                    // var d1 = new Date(),
                    // d2 = new Date(d1);
                    // d2.setMinutes(d1.getMinutes() + 30);
                    // var sure = d2.toLocaleString().substring(11, 19);
                    // var text = " Kontrol edilecek sipariş kalmadı! Uygulama 30 dk bekletiliyor." + sure + " itibariyle tekrar başlatılacak.";
                    // HataKontrolYap(1, text);

                    // chrome.runtime.sendMessage({
                    // YenidenBaslat: true,
                    // });
                    // if (host == "www.amazon.com" || host == "www.abebooks.com") {
                    // SekmeKapat(2);
                    // }
                    // });
                    // } else {
                    if (cevap) {
                        if (cevap.hata) {
                            chrome.storage.local.set({ isStarted: false }, function () {
                                chrome.storage.sync.remove(['isStarted'], function () {})
                            })
                        }
                        console.log(cevap.result)
                        //console.table(cevap.result);
                        var data = cevap.data
                        if (Array.isArray(cevap.result)) {
                            localStorage.setItem('DataArray', JSON.stringify(cevap.result))

                            chrome.storage.sync.set(
                                {
                                    UrunID: cevap.result.ID,
                                    UrunGetirildi: true,
                                    Durum: 'TypeKontrol',
                                    KontrolUrl1: '',
                                    KontrolUrl2: '',
                                },
                                function () {
                                    linkKontrolCount = 0
                                    urunKontrolCount = 0
                                    var link1 = cevap.result.Url
                                    SekmeAc('https://www.amazon.com/gp/your-account/order-history?ref_=ya_d_c_yo')
                                    // if(data.KontrolUrl1 == data.KontrolUrl2)
                                    // {
                                    // chrome.storage.sync.set({
                                    // "Durum": "FiyatKontrol"
                                    // },function () {
                                    // SiparisLinkleriGetir(data.ID, data.AmazonUrl, data.AbeUrl);
                                    // });

                                    // }else{

                                    //SekmeAc(link1);

                                    //AmazonUrl = link1;
                                    //AbeUrl = data.AbeUrl;
                                    console.log('Sekmeler Açılacak!')
                                    if (host == 'www.amazon.com' || host == 'www.abebooks.com') {
                                        SekmeKapat(2)
                                    }
                                    //}
                                }
                            )
                        } else {
                            chrome.storage.local.set({ isStarted: false }, function () {
                                chrome.storage.sync.remove(['isStarted'], function () {})
                            })
                            dialogModal('Tracking bulunamadı!', 'red')
                        }
                    }
                    //}
                },
                error: function (req, textStatus, errorThrown) {
                    console.log('Ooops, something happened: ' + textStatus + ' ' + errorThrown)
                    UrunGetir()
                },
            })
        })
    }, 2000)
}

var count = 0
function BirinciLinkKontrol(KontrolUrl2, Sorgu) {
    var host = window.location.host
    let istek = []
    let istek2 = []
    var dataArray = JSON.parse(localStorage.getItem('DataArray'))
    console.table(dataArray)
    let loader = dialogModal(`Loading...`)
    let counter = 1
    $(loader).html(`Lütfen bekleyin!`)
    dataArray.map((data, index) => {
        console.log('https://www.amazon.com/gp/your-account/order-details?ie=UTF8&orderID=' + data.OrderNumber);
        
        istek.push(
            new Promise((resolve, reject) => {
                axios
                    .get(
                        'https://www.amazon.com/gp/your-account/order-details?ie=UTF8&orderID=' + data.OrderNumber,
                        {},
                        {
                            headers: {
                                cookie: document.cookie,
                            },
                        }
                    )
                    .then((response) => {
                        const dataHtml = response.data
                        html = $.parseHTML(dataHtml)

                        console.log($('#orderDetails div[data-component="purchasedItems"] .a-fixed-left-grid', html));
                        
                        
                        trackingId = ''
                        let div = $('#orderDetails div.od-shipments', html)
                
                        if (div.length > 0) div = div.find('div.shipment')
                        if (div.length == 0) div = $('#orderDetails div.shipment', html)

                        if(div.length == 0)
                            div = $(div).find('.a-fixed-left-grid.a-spacing-none, .a-fixed-left-grid.a-spacing-base')

                        if(div.length == 0)
                            div = $('#orderDetails div[data-component="purchasedItems"] .a-fixed-left-grid', html)
                        
                        console.log(div)
                        let products = []
                        div.each(function (index, item) {
                            let trackingLink = ''
                            let magazaAd = ''
                            let asin = ''
                            var $item = $(item)
                            var imgElements = $item.find('img:eq(0)')
                            //imgElements.each(function(index) {
                            // Img etiketinin src özelliğini alın
                            var src = imgElements.parent().attr('href')

                            if (src) asin = src.split('/')[3]
                            console.log(imgElements)

                            var closestAnchor = imgElements
                                .parent()
                                .parent()
                                .parent()
                                .parent()
                                .parent()
                                .parent()
                                .parent()
                                .parent()
                                .parent()
                                .prev()
                                .find('.track-package-button')
                                .find('a')

                            if (closestAnchor.length > 0) {
                                trackingLink = closestAnchor.attr('href')
                                console.log('En yakın takip bağlantısı: ' + trackingLink)
                            }
                            
                            if(trackingLink == '') {
                                trackingLink = $('div[data-component="shipmentConnections"] a:nth-child(1)', html).attr('href')
                            }

                            if ($item.find('div.yohtmlc-item.a-col-right > div:nth-child(3) > span > a')) {
                                magazaAd = $item
                                    .find('div.yohtmlc-item.a-col-right > div:nth-child(3) > span > a')
                                    .text()
                                    .trim()
                                    .split('\n')[0]
                            }

                            if (magazaAd == '' && $item.find('div.yohtmlc-item.a-col-right > div:nth-child(2) > span > a')) {
                                magazaAd = $item
                                    .find('div.yohtmlc-item.a-col-right > div:nth-child(2) > span > a')
                                    .text()
                                    .trim()
                                    .split('\n')[0]
                            }

                            if (magazaAd == '') {
                                magazaAd = $item.find('div[data-component="purchasedItemsRightGrid"] div[data-component="orderedMerchant"] a')
                                .text()
                                .trim()
                            }

                            if (magazaAd == '' && $item.find('div.a-fixed-left-grid-col.yohtmlc-item.a-col-right > div:nth-child(2) > span')) {
                        
                                magazaAd = $item
                                    .find('div.a-fixed-left-grid-col.yohtmlc-item.a-col-right > div:nth-child(2) > span')
                                    .text()
                                    .trim().split('Sold by: ')[1].trim();
                            }

                            if(asin == undefined) {
                                asin = $item
                                                .find("div[data-component='itemImage'] a")
                                                .attr('href')
                                                .split('/')
                                                if(asin.length > 2) {
                                                    asin = asin[2].split('?')[0]
                                                }else if(asin.length > 3) {
                                                    asin = asin[3].trim();
                                                }
                            }
                            
                            // Her bir img'in src'sini konsola yazdırın
                            console.log(
                                'OrderNumber:' +
                                    data.OrderNumber +
                                    ' için trackin url: ' +
                                    trackingLink +
                                    'magaza: ' +
                                    magazaAd
                            )
                            products.push({ url: trackingLink, asin: asin, magazaAd: magazaAd })
                        })
                        resolve({
                            products: products,
                            orderNumber: data.OrderNumber,
                        })
                        //});

                        // console.log('tracking:' + tracks[1] + ' kargoFirma:' + firm[1])
                    })
                    .catch((e) => {
                        reject(e)
                    })
            })
        )
    })
    Promise.all(istek)
        .then((values) => {
            console.log(values)
            $(loader).html('Kayıt ediliyor!')
            dataArray = values
            dataArray.map((data, index) => {
                data['products'].map((data2, index) => {
                    if (data2.url !== undefined) {
                        istek2.push(
                            new Promise((resolve, reject) => {
                                axios
                                    .get(
                                        'https://www.amazon.com' + data2.url,
                                        {},
                                        {
                                            headers: {
                                                cookie: document.cookie,
                                            },
                                        }
                                    )
                                    .then((response) => {
                                        const dataHtml = response.data
                                        html = $.parseHTML(dataHtml)
                                        trackingId = ''
                                        tracks = []
                                        if ($('.pt-delivery-card-trackingId', html)) {
                                            trackingId = $('.pt-delivery-card-trackingId', html).text()
                                        }
                                        if (trackingId == '') {
                                            trackingId = $('.carrierRelatedInfo-trackingId-text', html).text()
                                        }

                                        tracks = trackingId.split('Tracking ID:')
                                        if (!tracks) {
                                            tracks = trackingId.split('Tracking ID')
                                        }
                                        var firm = ''
                                        if ($(' div.pt-delivery-card-wrapper div:nth-child(1) h3', html)) {
                                            var shipfirm = $(
                                                'div.pt-delivery-card-wrapper  div:nth-child(1)  h3',
                                                html
                                            ).text()
                                            firm = shipfirm.split('Shipped with')
                                        }
                                        if ($('.carrierRelatedInfo-mfn-carrierNameTitle', html) && firm == '') {
                                            var shipfirm = $('.carrierRelatedInfo-mfn-carrierNameTitle', html).text()
                                            firm = shipfirm.split('Shipped with')
                                        }
                                        if ($('#carrierRelatedInfo-container', html).find('.widgetHeader').length > 0) {
                                            var shipfirm = $('#carrierRelatedInfo-container .widgetHeader', html).text()
                                            firm = shipfirm.split('Shipped with')
                                        }

                                        var h3 = $('h3').text()
                                        if (tracks[1] == null) {
                                            tracks[1] = '-1'
                                            firm[1] = ''
                                        }

                                        if (firm[1] == null) {
                                            console.log('kargo boş')
                                            var sonuc = tracks[1].indexOf('TBA')
                                            if (sonuc > -1) {
                                                firm[1] = 'Amazon'
                                            }
                                        }
                                        if (tracks[1] === undefined || tracks[1] === '') {
                                            tracks[1] = '-1'
                                        }
                                        $(loader).html(`İşleniyor : ${counter + '/' + dataArray.length}`)
                                        counter++
                                        console.log('kargoFirm:' + firm[1].trim(), 'trackingNumber:' + tracks[1].trim())
                                        resolve({
                                            kargoFirm: firm[1].trim(),
                                            trackingNumber: tracks[1].trim(),
                                            asin: data2.asin,
                                            magazaAd: data2.magazaAd,
                                            orderNumber: data.orderNumber,
                                        })
                                        // console.log('tracking:' + tracks[1] + ' kargoFirma:' + firm[1])
                                    })
                                    .catch((e) => {
                                        reject(e)
                                    })
                            })
                        )
                    }
                })
            })

            Promise.all(istek2)
                .then((values) => {
                    console.log(values)
                    $(loader).html('Kayıt ediliyor!')
                    SiparisTamamla(values)
                })
                .catch((e) => {
                    console.log(e, 'Hata!')
                    $(loader).remove()
                })
        })
        .catch((e) => {
            console.log(e, 'Hata!')
            $(loader).remove()
        })

    // if (host == 'www.amazon.com') {
    //     var rank = ''
    //     var aramaTextBox = $('#twotabsearchtextbox')
    //     var myElem = document.querySelector('head > title')
    //     if (myElem != null) {
    //         if (myElem.textContent.trim() == 'Page Not Found') {
    //             // chrome.storage.sync.set({
    //             // 'KontrolUrl1': 'Hardcover',
    //             // 'KontrolUrl2': 'Hardcover',
    //             // 'Titles' : 'deneme' ,
    //             // 'Price' : "",
    //             // 'Review' : "",
    //             // 'Rating' : "",
    //             // 'brokenlink':"1"
    //             // }, function () {
    //             // //console.log("Birinci url kontrol edildi: " + deger);
    //             // console.log("Fiyat:"+fiyat+" Review:"+review+" Rating:"+rating);
    //             // SekmeKapat(1);
    //             // });
    //         } else if (aramaTextBox.length) {
    //             trackingId = ''
    //             if ($('#carrierRelatedInfo-container .pt-delivery-card-trackingId')) {
    //                 var trackingId = $('#carrierRelatedInfo-container .pt-delivery-card-trackingId').text()
    //             }
    //             if (trackingId == '') {
    //                 var trackingId = $('#carrierRelatedInfo-container .carrierRelatedInfo-trackingId-text').text()
    //             }

    //             var tracks = trackingId.split('Tracking ID:')
    //             if (!tracks) {
    //                 var tracks = trackingId.split('Tracking ID')
    //             } else {
    //                 ;('#carrierRelatedInfo-container .carrierRelatedInfo-trackingId-text')
    //             }
    //             var firm = ''
    //             if (
    //                 $(
    //                     '#carrierRelatedInfo-container > div > section > div.pt-delivery-card-wrapper > div:nth-child(1) > h3',
    //                 )
    //             ) {
    //                 var shipfirm = $(
    //                     '#carrierRelatedInfo-container > div > section > div.pt-delivery-card-wrapper > div:nth-child(1) > h3',
    //                 ).text()
    //                 firm = shipfirm.split('Shipped with')
    //             }
    //             if ($('#carrierRelatedInfo-container .carrierRelatedInfo-mfn-carrierNameTitle') && firm == '') {
    //                 var shipfirm = $('#carrierRelatedInfo-container .carrierRelatedInfo-mfn-carrierNameTitle').text()
    //                 firm = shipfirm.split('Shipped with')
    //             }
    //             if ($('#carrierRelatedInfo-container').find('.widgetHeader').length > 0) {
    //                 var shipfirm = $('#carrierRelatedInfo-container .widgetHeader').text()
    //                 firm = shipfirm.split('Shipped with')
    //             }
    //             // if(tracks[1]==null && firm[1]==null)
    //             // {
    //             // tracks[1]="Bulunamadı";
    //             // }
    //             var h3 = $('h3').text()
    //             if (tracks[1] == null) {
    //                 tracks[1] = '-1'
    //                 firm[1] = ''
    //             }

    //             if (firm[1] == null) {
    //                 console.log('kargo boş')
    //                 var sonuc = tracks[1].indexOf('TBA')
    //                 if (sonuc > -1) {
    //                     firm[1] = 'Amazon'
    //                 }
    //             }
    //             if (tracks[1] === undefined || tracks[1] === '') {
    //                 tracks[1] = '-1'
    //             }

    //             // var shipfirm=$(".carrierRelatedInfo-mfn-carrierNameTitle").text();
    //             // firm=shipfirm.split("Shipped with");

    //             chrome.storage.sync.set(
    //                 {
    //                     KontrolUrl1: 'Hardcover',
    //                     KontrolUrl2: 'Hardcover',
    //                     Titles: 'deneme',
    //                     tracking: tracks[1],
    //                     kargoFirma: firm[1],
    //                 },
    //                 function () {
    //                     console.log('tracking:' + tracks[1] + ' kargoFirma:' + firm[1])
    //                     SekmeKapat(1)
    //                 },
    //             )
    //         } else {
    //             console.log('Yenile')
    //             //window.location.reload();
    //         }
    //     } else {
    //         console.log('Yenile')
    //         //window.location.reload();
    //     }
    // } else {
    //     if (document.querySelector('.additionalShippingInfoBtn'))
    //         document.querySelector('.additionalShippingInfoBtn').click()

    //     setTimeout(function () {
    //         if (document.querySelector('#tracking-details > div > div.tracking-controls.system-font > button'))
    //             document.querySelector('#tracking-details > div > div.tracking-controls.system-font > button').click()
    //         console.log('1')

    //         $('.iframeTrackingPlaceholder iframe').attr('id', 'myiframe')
    //         //find iframe
    //         let iframe = $('#myiframe')

    //         //find button inside iframe
    //         let button = iframe.contents().find('button')
    //         console.log(button)
    //         //trigger button click
    //         button.trigger('click')

    //         setTimeout(function () {
    //             //document.querySelector("#tracking-details > div > div.tracking-controls.system-font > button").click();
    //             var tracking = iframe.contents().find('div.tracking-details--carrier').text().split('tracking #')[1]
    //             var shippingCarrier = iframe
    //                 .contents()
    //                 .find('div.tracking-details--carrier')
    //                 .text()
    //                 .split('tracking #')[0]
    //                 .trim()
    //             chrome.storage.sync.set(
    //                 {
    //                     KontrolUrl1: 'Hardcover',
    //                     KontrolUrl2: 'Hardcover',
    //                     Titles: 'deneme',
    //                     tracking: tracking,
    //                     kargoFirma: shippingCarrier,
    //                 },
    //                 function () {
    //                     console.log('tracking:' + tracking + ' kargoFirma:' + shippingCarrier)
    //                     SekmeKapat(1)
    //                 },
    //             )
    //         }, 2000)
    //     }, 5000)
    // }

    // HataKontrolYap(75);
    // chrome.storage.local.get(["SekmeCount"], function (item) {

    // count = item.SekmeCount + 1;
    // chrome.storage.local.set({
    // 'SekmeCount': count
    // }, function () {
    // });

    // if(count == 7){
    // chrome.storage.sync.set({
    // 'KontrolUrl1': 'Hardcover',
    // 'KontrolUrl2': 'Hardcover',
    // 'Titles' : 'deneme'
    // }, function () {
    // //console.log("Birinci url kontrol edildi: " + deger);
    // SekmeKapat(1);
    // });
    // }else{
    // SekmeKapat(1);
    // }
    // });
}

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

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

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

            if (item.KontrolUrl1 == item.KontrolUrl2) {
                console.log('doğru')
                //WHataliUrun(id);
                SiparisLinkleriGetir(id, AmazonUrl, AbeUrl)
            } else {
                if (
                    (item.KontrolUrl1 == 'Board book' || item.KontrolUrl1 == 'Hardcover') &&
                    (item.KontrolUrl2 == 'Board book' || item.KontrolUrl2 == 'Hardcover')
                ) {
                    console.log('deneme dogrusu')
                    //WHataliUrun(id);
                    SiparisLinkleriGetir(id, AmazonUrl, AbeUrl)
                } else {
                    console.log('yanlış')
                    HataliUrun(id)
                    //SiparisLinkleriGetir(id, AmazonUrl, AbeUrl);
                }
            }
        })
    }
}

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

var AbeUrunList = []

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

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

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

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

var AmzUrunList = []

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

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

    var host = window.location.host

    if (host != 'www.amazon.com' && host != 'www.abebooks.com') {
        chrome.storage.sync.get(['UrunID'], function (item) {
            UrunID = item.UrunID
        })
        chrome.storage.local.get(['AmzUrunList', 'AbeUrunList'], function (item) {
            var Amazon = item.AmzUrunList
            var Abebook = item.AbeUrunList
            var orderArray = [[...Amazon], [...Abebook]]
            console.log(orderArray)
            var stringArray = JSON.stringify(orderArray)
            $.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: UrunID,
                    orderArray: stringArray,
                    tip: 'newOrderFiltre',
                },
                success: function (cevap) {
                    if (cevap.hata) {
                        console.log('Hata')
                    } else {
                        if (cevap.result) {
                            console.log('Sipariş listesi başarıyla alındı! UrunListeleriniGonder()')
                            // fiyatkontroldeki veriler duruma göre silinecek. lcaol storage sync
                            var gelenJson = cevap.result
                            if (gelenJson['1'] != null && gelenJson['1'] != undefined) {
                                console.log('Sipariş Alınacak')
                                console.log(gelenJson[0])
                                console.log(gelenJson[1])
                                var SiparisListesiLastIndex = parseInt(gelenJson['1'].length) - 1
                                var SiparisIndex = 0
                                chrome.storage.sync.set(
                                    {
                                        Durum: 'UrunAl',
                                        AdresEklendi: false,
                                    },
                                    function () {
                                        chrome.storage.local.set(
                                            {
                                                AdresBilgileri: gelenJson[0],
                                                SiparisBilgileri: gelenJson[1],
                                                SiparisListesiLastIndex: SiparisListesiLastIndex,
                                                SiparisIndex: SiparisIndex,
                                            },
                                            function () {
                                                console.log('Siparişler alınacak. ')
                                                UrunAl(0)
                                            }
                                        )
                                    }
                                )
                            } else {
                                //localstorage'ları temizle

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

function AmzItemNotAdded() {
    console.log('AmzItemNotAdded()')
    var isNotAdded = $('#huc-v2-order-row-confirm-text').text().trim()
    if (isNotAdded == 'Not added') {
        //birse git ikiyse sil?
        var amzlink = 'https://www.amazon.com/gp/cart/view.html?'
        var params = 'PgNm=Amz&Sil=True'
        var link = amzlink + params
        SayfaGit(link, 1)
    }
}

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

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

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

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

function OriginalAddressCheckButtonClick() {
    setTimeout(function () {
        $('input[type=submit][value=SAVE_ADDRESS]').click()
        $('input[type=submit][value=SAVE_ADDRESS]').trigger('click')
        // $(".Butonlar > div").children().eq(0).click();
        // $(".Butonlar > div").children().eq(0).trigger("click");
        // $(".Butonlar > div").children().eq(0).find("input").trigger("click");
        // $(".Butonlar > div").children().eq(0).find("input").click();
        // $(".Butonlar > div").children().eq(0).find("input").trigger("click");
        // $(".Butonlar > div").children().eq(0).find("input").next("span").click();
        // $(".Butonlar > div").children().eq(0).find("input").next("span").trigger("click");
        AmzOrderComplete()
    }, 1000)
}

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

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

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

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

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

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

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

var AmzOrderCompleteCheckCount = 0

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

var AmzOrderCompleteCheckCount = 0

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

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

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

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

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

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

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

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

        Price = Price.toFixed(2)

        console.log('Localdeki:' + LocaldekiUrun.Condition + ' ' + LocaldekiUrun.Seller + ' ' + LocaldekiUrun.Price)
        console.log('Sayfadaki:' + Condition + ' ' + Seller + ' ' + Price)
        if (NPrice == null) {
            NPrice = IstenilenFiyat
        }
        if (
            (LocaldekiUrun.Condition == Condition &&
                LocaldekiUrun.Seller == Seller &&
                Price <= parseFloat(LocaldekiUrun.Price).toFixed(2)) ||
            parseFloat(Price).toFixed(2) <= parseFloat(NPrice).toFixed(2)
        ) {
            console.log('İki ürün aynı işlemlere devam edilecek! (Abebook)')

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

            var abelink = 'https://www.abebooks.com' + a
            var params = '&PgNm=Abe&Basket=True'
            var link = abelink + params

            chrome.storage.sync.set(
                {
                    AbeSepetUrunLink: link,
                    NextPrice: NPrice,
                },
                function () {
                    SayfaGit(link, 1)
                }
            )
        } else {
            console.log('İki ürün aynı değil, diğer ürüne geç! (Abebook)')
            UrunAl(0)
        }
    })
}

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

    var SepetCount = $('#bskc').text()
    console.log(SepetCount)
    if (SepetCount != undefined && SepetCount.length > 0) {
        if (parseInt(SepetCount) > 1) {
            console.log('Sepetteki ürün 1 dan fazla')
            $('.saveDelete').find('.secondarybutton').click()
            $('.saveDelete').find('.secondarybutton').trigger('click')
        } else {
            console.log('Sepetteki ürün adeti 1. İşlemlere devam edilecek. AbeBasketPage()')
            var ErrorMessage = $('.errorMessage').text()
            var itemSold = 'Item sold'
            var itemSoldDurum = ErrorMessage.indexOf(itemSold) !== -1
            var itemSoldText = $('.status > .alert').text()
            if (itemSoldDurum) {
                //|| itemSoldText.length > 0 && itemSoldText == "Item already in Basket"
                console.log('Sepetteki ürün adeti 1. Fakat ürün satılmış. Yeni Ürüne geçilecek! AbeBasketPage()')
                // UrunZararYaz();
                UrunAl(0)
            } else {
                console.log('Sepetteki ürün adeti 1. Ürün stokta mevcut! AbeBasketPage()')
                var SepetKargoAdres = 'https://www.abebooks.com/servlet/ShippingAddress?AddAdres=true&PgNm=Abe'
                SayfaGit(SepetKargoAdres, 1)
            }
        }
    } else {
        var ErrorMessage = $('.errorMessage').text()
        var itemSold = 'Item sold'
        var itemSoldDurum = ErrorMessage.indexOf(itemSold) !== -1
        if (itemSoldDurum) {
            console.log('ürün satılmış. Yeni Ürüne geçilecek! AbeBasketPage()')
            // UrunZararYaz();
            UrunAl(0)
        } else {
            console.log('Sepet Boş. Ürün tekrar alınacak! AbeBasketPage()')
            chrome.storage.sync.get(['AbeSepetUrunLink'], function (item) {
                console.log(item.AbeSepetUrunLink)
            })
        }
    }
}

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

    var SepetCount = $('#bskc').text()
    if (SepetCount != undefined && SepetCount.length > 0) {
        if (parseInt(SepetCount) != 0) {
            console.log("Sepetteki ürün 0'dan fazla. Sepet boşaltılacak! AbeBasketBosalt()")
            $('.saveDelete').find('.secondarybutton').click()
            $('.saveDelete').find('.secondarybutton').trigger('click')
        } else {
            console.log('Sepetteki ürün 0 (Code:1)')
        }
    } else {
        if ($('.saveDelete').length > 0) {
            $('.saveDelete').find('.secondarybutton').click()
            $('.saveDelete').find('.secondarybutton').trigger('click')
        } else {
            console.log('Sepet Boş. Ürün tekrar alınacak. AbeBasketBosalt()')
            chrome.storage.sync.get(['AbeSepetUrunLink'], function (item) {
                console.log(item.AbeSepetUrunLink)
                SayfaGit(item.AbeSepetUrunLink, 1)
            })
        }
    }
}
function AbeAdresSilme() {
    console.log($('#delete-address-link-10'))
    if ($('#delete-address-link-10').length) {
        setTimeout(function () {
            $('#delete-address-link-10').click()
            $('#delete-address-link-10').trigger('click')
        }, 5000)
        var url = 'https://www.abebooks.com/servlet/ShippingAddress?AddAdres=true&PgNm=Abe'
        getSayfa(url)
    } else {
        AbeAdresEkle()
    }
}
function AbeAdresEkle() {
    console.log('AbeAdresEkle()')
    chrome.storage.local.get(['AdresBilgileri'], function (item) {
        var Adressler = $('.address')
        var ToplamAdres = $('.address').length - 3
        console.log(ToplamAdres)

        Adressler.each(function (index) {
            if (ToplamAdres > 10) {
                if (index != 0 && index < ToplamAdres) {
                    // $('#delete-address-link-'+index).click();
                    // $('#delete-address-link-'+index).trigger('click');
                    // console.log('ededsed');
                    // var href = $(this).children("a").eq(1).attr("href");
                    // var url = "https://www.abebooks.com" + href;
                    // console.log(url);
                    // getSayfa(url);
                }
            }
        })

        chrome.storage.sync.set(
            {
                AdresEklendi: true,
            },
            function () {
                var data = item.AdresBilgileri
                $('#countryisocode').val('USA').prop('selected', true)
                $('input[name=firstandlastname]').val(data.Name)
                $('input[name=address1]').val(data.Adres1)
                $('input[name=address2]').val(data.Adres2)
                $('input[name=zipcode]').val(data.PKod)
                $('input[name=city]').val(data.City)
                $('input[name=phone]').val(data.Phone)

                // $('#provstate').val("ME").prop('selected', true);
                $('#provstate').val(data.State).prop('selected', true)
                // $("input[name=setAsDefault]").prop('checked', true);
                $('#setAsDefault0').prop('checked', true)
                $('#savesubmitid').click()
                $('#savesubmitid').trigger('click')
                console.log('Adres ekledim!')
            }
        )

        // var link = "https://www.abebooks.com/servlet/OrderSummary?Complete=true&PgNm=Abe"
        //  SekmeAc(link);
        // console.log("Adres ekledim!");
        // var link = "https://www.abebooks.com/servlet/OrderSummary?Billing=true&PgNm=Abe"
        //  SekmeAc(link);
    })
}

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

function AbeSaveBilling() {
    console.log('AbeSaveBilling()')
    if ($('#saveButton').length > 0) {
        $('#saveButton').click()
        $('#saveButton').trigger('click')
    } else {
        $('#savesubmitid').click()
        $('#savesubmitid').trigger('click')
    }
}

function AbeOrderComplete() {
    console.log('AbeOrderComplete();')
    $('.col-sm-5 .small-plus').addClass('shippinge')
    chrome.storage.sync.get(['UrunID', 'UrunFiyat', 'NextPrice'], function (item) {
        waitForElement('.price-muted', function () {
            var LastPrice = $('div.medium.price-muted.mt-lg.mb-lg > div.pull-right').text().split('$')['1']
            var DLastPrice = parseFloat(LastPrice)
            var DUrunFiyat = parseFloat(item.UrunFiyat)
            var DNextPrice = parseFloat(item.NextPrice)
            console.log(DLastPrice)
            console.log(DUrunFiyat)
            console.log(DNextPrice)
            if (DLastPrice <= DUrunFiyat || DLastPrice <= DNextPrice) {
                console.log('AbeOrderComplete Button tıklanacak!')

                var kargoadres = $('.shippinge').text().length
                var faturaadres = $('.optimizely-billing-address').text().length

                console.log(faturaadres)
                console.log('tıklanacak')

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

                UrunAl(0)
            }
        })
    })
}

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

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

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

    return strText
}

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

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

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

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

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

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

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

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

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

var HataKontrol

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

                $.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(75);
// chrome.storage.local.get(["RunCount"], function (item) {
// RunCount=item.RunCount
// });
// console.log(RunCount+1);

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

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

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